2
我想获得过滤器列表上的2个属性,其中第一个属性是一个值,第二个属性是另一个列表的对象包含一定的值属性。复杂的Linq查询来选择列表项目与另一个列表属性包含值
如下面我想获得的List<Class1>
一个列表,其中field1 == "f1"
和Field3包含Class2中的项目,其中财产c2 == 2
我可以用得到的SelectMany接近但是这给List<Class2>
,而不是父母的Class1。
这可能吗?
示例代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Class2 c2_1 = new Class2() {c1 = "c1", c2 = 2};
Class2 c2_2 = new Class2() {c1 = "c2", c2 = 4};
Class2 c2_3 = new Class2() { c1 = "c3", c2 = 1 };
Class2 c2_4 = new Class2() { c1 = "c4", c2 = 3 };
Class2 c2_5 = new Class2() { c1 = "c5", c2 = 2 };
Class2 c2_6= new Class2() { c1 = "c6", c2 = 4 };
List<Class1> class1List = new List<Class1>()
{
new Class1() { field1 = "f1", field2 = "Want This Class", field3 = new List<Class2>() { c2_1, c2_2 } },
new Class1() { field1 = "f1", field2 = "Do Not Want This Class", field3 = new List<Class2>() { c2_3, c2_4 } },
new Class1() { field1 = "f1", field2 = "Want This Class", field3 = new List<Class2>() { c2_5, c2_6} }
};
//Want list of Class1 where field1 == "f1" && field3 List contains an item with property c2 == 2 (Should be list of 2 Class1 items)
//Doesn't work
//var list1 = class1List.Where(x => x.field1 == "f1" && x.field3.c2)
//Close, but gives a list of Class2 items but need list of parent Class1
var list2 = class1List.Where(x => x.field1 == "f1").SelectMany(x => x.field3.Where(d => d.c2 == 2)).ToList();
}
}
public class Class1
{
public string field1 { get; set; }
public string field2 { get; set; }
public List<Class2> field3 { get; set; }
}
public class Class2
{
public string c1 { get; set; }
public int c2 { get; set; }
}
}