如何在linq中展平特定组并选择所有元素,并且仅从其他组中选择

时间:2013-05-23 17:24:42

标签: c# linq

我有一个项目列表,其中一些项目可能具有特定项目属性的null /零值。我正在按其他财产分组项目。然后我想要的是选择我的属性!= null /零的那些组的First()元素,以及该属性等于null / 0的组中的所有项。怎么做?

1 个答案:

答案 0 :(得分:0)

由于您的问题中没有相关数据和代码,请让我通过示例给出一般答案:

首先,让我们有一个示例类:

class Test
{
    public int? First { get; set; }
    public int? Second { get; set; }
    public int? Third { get; set; }
}

...然后让我们填写它:

        List<Test> list = new List<Test> 
        {
            new Test {First = null, Second = 1, Third = 2},
            new Test {First = 5, Second = 3, Third = 4},
            new Test {First = 6, Second = null, Third = 8},
            new Test {First = null, Second = 2, Third = 5},
            new Test {First = 8, Second = null, Third = 14},
            new Test {First = 21, Second = 2, Third = null},
            new Test {First = 5, Second = 4, Third = 2},
            new Test {First = 9, Second = 0, Third = 8}
        };

...现在你可以这样做(如果我理解你的问题):

        var result = list
            .GroupBy(x => x.First) //grouping by First property
            .Select(y => new
                               {
                                   FirstNonNull = y.FirstOrDefault(z => z.Second != null), // first null in group by Second property
                                   AllNull = y.Where(f => f.Second == null) // all null in group by Second property
                               }
            );