复杂Linq查询选择列表项与另一个包含值的列表属性

时间:2016-05-17 23:04:47

标签: c# linq

我想在2个属性上过滤一个列表,其中第一个属性是值,第二个属性是另一个包含属性的特定值的对象列表。

例如,我想获得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; }
    }
}

1 个答案:

答案 0 :(得分:3)

如果Any()包含至少一个field3值等于true的项目,您可以在field3上应用c2返回2:< / p>

....
var list2 = class1List.Where(x => x.field1 == "f1" &&
                                  x.field3.Any(d => d.c2 == 2))
                      .ToList();
foreach (var class1 in list2)
{
    Console.WriteLine(class1.field2);
}

输出:

Want This Class
Want This Class