首先,我对 LINQ 非常陌生。
我有一个包含如下数据的列表:
列表
list[0] = id=1,block=10,sg=320,dc=null
list[1] = id=1,block=10,sg=null,dc=320
list[2] = id=2,block=15,sg=400,dc=null
list[3] = id=2,block=15,sg=null,dc=400
我想更新此列表:
if(sg where block=x and id=y is null)
then set sg = (sg where block=x and id=y is not null)
and similarly for dc
期望的结果:
list[0] = id=1,block=10,sg=320,dc=320
list[1] = id=2,block=15,sg=400,dc=400
注意:id 和 block 是此处的识别因素。
类别:
public class dcsg
{
public long id { get; set; }
public Nullable<decimal> dcvalue { get; set; }
public Nullable<decimal> sgvalue { get; set; }
public Nullable<int> revision { get; set; }
public Nullable<long> timestampid { get; set; }
public decimal fuelcost { get; set; }
public Nullable<short> isdeleted { get; set; }
public Nullable<long> blockno { get; set; }
public int stageid { get; set; }
}
最佳答案
您可以使用 Linq
、GroupBy
来实现此目的。
lists = lists.GroupBy(x=> new {x.id, x.blockno})
.Select(x=>
{
var sg1 = x.FirstOrDefault(f=>f.sgvalue.HasValue);
var dc1 = x.FirstOrDefault(f=>f.dcvalue.HasValue);
return new dcsg() // create class instance if have one.
{
id= x.Key.id,
blockno= x.Key.blockno,
sgvalue = sg1==null? null; sg1.sgvalue,
dcvalue = dc1==null? null; dc1.dcvalue,
// copy other properties (if needed).
};
})
.ToList();
显然,代码片段是基于两个假设编写的。
- 如果同一 block 出现多个
sg
,首先 sg 将被占用(但这可以根据需要更改)。 - 根据您的示例,
id,block
用于对列表项进行分组。
关于c# - 通过自连接更新 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37049463/