c# - 通过自连接更新 List<T>?

标签 c# asp.net .net linq generics

首先,我对 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; }
    }

最佳答案

您可以使用 LinqGroupBy 来实现此目的。

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();  

显然,代码片段是基于两个假设编写的。

  1. 如果同一 block 出现多个 sg首先 sg 将被占用(但这可以根据需要更改)。
  2. 根据您的示例,id,block 用于对列表项进行分组。

关于c# - 通过自连接更新 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37049463/

相关文章:

c# - 可选参数必须是引用类型、可空类型或声明为可选参数。参数名称 : parameters`

asp.net - 通过 UpdatePanel 异步回发后重新加载外部 javascript

.net - AspNetCompiler MSBuild 任务中的 VirtualPath - 它是否必须等于最终部署的虚拟路径?

c# - 将imageUrl转换为byte[]进行缓存

c# - OpenRasta 可以与现有的 Web 应用程序一起运行吗?

c# - 注入(inject)横切关注点有哪些不同的方法?

.net - 如何在插入时忽略实体模型中的特定字段?

c# - WinRT : Binding a RTF String to a RichEditBox

c# - 用于匹配引号和单引号的正则表达式

c# - 在 C# 中使用函数返回两个字符串