0

我有来自数据库的实体集合,其中包含某些重复项,例如一个带有值的序列和其他带有空值的序列。我想删除空序列。我已经厌倦moreLINQ了,DistinctBy但我的情况仍然不令人满意。

我有一个来自结果集的列表。

Result: Id=1, Name="Test1", Status="New", Values=NULL 
Result: Id=1, Name="Test1", Status="Assigned", Values=123 
Result: Id=2, Name="Test2", Status="New", Values=NULL 
Result: Id=2, Name="Test2", Status="Assigned", Values=698 
Result: Id=3, Name="Test3", Status="Assigned", Values=569 
Result: Id=4, Name="Test4", Status="New", Values=NULL 
Result: Id=5, Name="Test5", Status="Assigned", Values=156

我想始终通过跳过具有空值或New状态的重复项来检索以下输出。

Result: Id=1, Name="Test1", Status="Assigned", Values=123 
Result: Id=2, Name="Test2", Status="Assigned", Values=698 
Result: Id=3, Name="Test3", Status="Assigned", Values=569 
Result: Id=4, Name="Test4", Status="New", Values=NULL 
Result: Id=5, Name="Test5", Status="Assigned", Values=156
4

2 回答 2

0

Group byId并获取按 排序的每个组的第一条记录Status

var records = new[]
{
    (Id:1, Name:"Test1", Status:"New", Values:default(int?)),
    (Id:1, Name:"Test1", Status:"Assigned", Values:123),
    (Id:2, Name:"Test2", Status:"New", Values:default(int?)),
    (Id:2, Name:"Test2", Status:"Assigned", Values:698),
    (Id:3, Name:"Test3", Status:"Assigned", Values:569),
    (Id:4, Name:"Test4", Status:"New", Values:default(int?)),
    (Id:5, Name:"Test5", Status:"Assigned", Values:156),
};

var result = records
    .GroupBy(r => r.Id)
    .Select(r => r.OrderBy(x => x.Status).First());

结果:

Id  Name    Status      Values
------------------------------
1   Test1   Assigned    123
2   Test2   Assigned    698
3   Test3   Assigned    569
4   Test4   New         null
5   Test5   Assigned    156
于 2020-09-04T08:51:04.683 回答
0

你可以像下面这样

DOTNETFIDDLE工作代码

var modified = listOfValues
                .GroupBy(x => x.Id)
                .Select(x => x.OrderByDescending(x => x.Values ?? int.MinValue).FirstOrDefault());

结果:

在此处输入图像描述

于 2020-09-04T07:42:31.407 回答