使用两个列表中的linq匹配和更新值?

时间:2014-01-24 13:37:10

标签: c# performance linq c#-4.0

您好我是c#和Linq的新手。如果某个属性的值与其他列表属性的值匹配,我试图更新一个列表。

假设我有一个列表firstlist

   Name      code        
   ABC       101         
   DEF       201         
   GHI       301
   JKL       401
   MNO       101 

第二个列表为secondlist

  description       Code
    IT               101
    ADMIN            201
    Develeopment     301
    Testing          401
    Service          501

我希望我的结果列表为

    Name      code        
    ABC       101 IT        
    DEF       201 ADMIN       
    GHI       301 Develeopment
    JKL       401 Testing
    MNO       101 IT

我尝试过这样的事情,

    var query = firstlist.Select(x => { x.Code = 101; return x.Code.ToString()+"IT"; })

但是我希望匹配secondlist中的代码代替101以及匹配代码我希望使用firstlist我更新code+description代码如果有人建议任何方式或链接指导我会很棒,那么我知道怎么做。

** * **** 更新 < EM> * ** * ***

我想说的是@Sergey建议的

   from x in firstlist
   join y in secondList
   on x.code equals y.Code
   select new {
       x.Name,
      code = String.Format("{0} {1}", y.Code, y.description)   
  }

取代这个我可以做这样的事情

   from x in firstlist
   join y in secondList
   on x.code equals y.Code
   select x.code = String.Format("{0} {1}", y.Code, y.description)   

只会更新现有的listone,而不是为每场比赛创建新实体

4 个答案:

答案 0 :(得分:6)

使用Enumerable.Join获取两个列表中匹配的项目:

from x in firstlist
join y in secondList
   on x.code equals y.Code
select new {
   x.Name,
   code = String.Format("{0} {1}", y.Code, y.description)   
}

更新第一个列表中的对象:

var query = from x in firstlist
            join y in secondList
                on x.code equals y.Code
            select new { x, y };

foreach(var match in query)
   match.x.Code = String.Format("{0} {1}", match.y.Code, match.y.description);

答案 1 :(得分:0)

Code似乎是int,然后您无法将其更改为包含代码+说明的string。所以这种方法假定它是string

您可以使用Enumerable.Join仅根据Code获取两者中的项目。然后最有效的方法是使用一个简单的循环来使用新值更新属性:

var firstInSecond = from first in firstlist
                    join second in secondList
                    on first.Code equals second.Code
                    select new { first, second };
foreach (var x in firstInSecond)
    x.first.Code = string.Format("{0} {1}", x.second.Code, x.second.Description);

答案 2 :(得分:0)

暂时将描述列添加到firstlist或将其克隆到anther表

firstlist.Columns.Add("description");
Datatable joinedTable = from first in firstlist
                    join second in secondList
                    on first.Code equals second.Code
                    select new DataRow[] { first , second }).Select(resultSet =>
                                          {
                                              resultSet[0]["description"] = resultSet[1]["description"];
                                              return resultSet[0];
                                          }).CopyToDataTable();

答案 3 :(得分:0)

对于使用AND查询在2个列表上进行JOIN更新,您可以使用JOIN和Where条件,例如,请检查以下内容, https://codeshowtime.blogspot.com/2020/01/linq-tricks.html