LINQ:如何通过某个对象属性值选择整个列表列表

时间:2018-03-07 10:01:24

标签: c# list linq

这可能很容易,但我找不到答案 我有List<List<myclass>>,如何通过特定的值对象属性值提取整个列表?

例如,请参阅我的草稿代码,如何根据t2对象属性提取整个(该列表中的所有对象)mc7列表?

我只是成功提取mc7对象,而不是result变量中的List列表。

class myclass
{
    public DateTime SomeDate;
    public string SomeString;
}

static void Main(string[] args)
{
    List<List<myclass>> L = new List<List<myclass>>();
    List<myclass> t = new List<myclass>();

    myclass mc = new myclass() { SomeString = "5", SomeDate = DateTime.Now};
    myclass mc1 = new myclass() { SomeString = "12", SomeDate = DateTime.Now.AddDays(1) };
    myclass mc2 = new myclass() { SomeString = "123", SomeDate = DateTime.Now.AddDays(2) };
    myclass mc3 = new myclass() { SomeString = "77", SomeDate = DateTime.Now.AddDays(3) };
    myclass mc4 = new myclass() { SomeString = "882", SomeDate = DateTime.Now.AddDays(4) };

    t.Add(mc);
    t.Add(mc1);
    t.Add(mc2);
    t.Add(mc3);
    t.Add(mc4);

    L.Add(t);

    List<myclass> t2 = new List<myclass>();

    myclass mc5 = new myclass() { SomeString = "166", SomeDate = DateTime.Now.AddDays(500) };
    myclass mc6 = new myclass() { SomeString = "344", SomeDate = DateTime.Now.AddDays(501) };
    myclass mc7 = new myclass() { SomeString = "123", SomeDate = DateTime.Now.AddDays(502) };
    myclass mc8 = new myclass() { SomeString = "234", SomeDate = DateTime.Now.AddDays(503) };
    myclass mc9 = new myclass() { SomeString = "123", SomeDate = DateTime.Now.AddDays(504) };

    t2.Add(mc5);
    t2.Add(mc6);
    t2.Add(mc7);
    t2.Add(mc8);
    t2.Add(mc9);

    L.Add(t2);

    var target1 = "123";
    var date = DateTime.Now.AddDays(502).Date;

    var result = L.SelectMany(x => x)
        .Where(y => y.SomeString == target1 && y.SomeDate.Date == date).Select(x=>x).ToList();

}

2 个答案:

答案 0 :(得分:1)

由于您要搜索特定列表,因此应避免使用SelectMany

var result = L
     .Where(l=>l.Any(y => y.SomeString == target1 && y.SomeDate.Date == date))
     .FirstOrDefault();

答案 1 :(得分:1)

如果您想要包含至少一个与谓词匹配的对象的列表:

var result = L.Where(list => list.Any(x => x.SomeString == target1 && x.SomeDate.Date == date)).ToList();

如果您只想要一个列表,请将ToList替换为FirstOrDefault

如果您希望包含至少一个与谓词匹配的对象的列表,那些列表应该只包含这些对象,那么所有其他不匹配的对象都将被过滤掉:

var result = L
    .Select(list => list.Where(x => x.SomeString == target1 && x.SomeDate.Date == date).ToList())
    .Where(list => list.Any())
    .ToList();