如何在linq中平坦特定组并选择所有元素,并且只首先从其他组中选择
本文关键字:选择 元素 其他 linq | 更新日期: 2023-09-27 18:15:08
我有一个项目列表,其中一些项目可能具有特定项目属性的null/零值。我正在按其他属性分组项目。然后我想要的是,选择属性!= null/0的组中的First()元素,以及属性= null/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
}
);