代码之家  ›  专栏  ›  技术社区  ›  leora Matt Lacey

将属性从一个集合设置为另一个集合

  •  0
  • leora Matt Lacey  · 技术社区  · 14 年前

    我有两个共谋

    List<Application>  myApps;
    
    List<Application> yourApps;
    

    这些列表有重叠的数据,但它们来自不同的源,并且每个源都缺少一些字段数据。

    应用 对象有一个名为 说明

    两个集合都有一个名为

    我想看看是否有LINQ解决方案:

    我的应用程序 看看钥匙,看看里面有没有 你的应用程序 . 如果是的话,我就要 属性,并在上设置应用程序的description属性 同样的价值

    5 回复  |  直到 14 年前
        1
  •  2
  •   Anthony Pegram    14 年前

    可以使用连接:

    foreach(var pair in from m in myApps
                        join y in yourApps on m.Key equals y.Key
                        select new { m, y }) {
        pair.m.Description = pair.y.Description;
    }
    
        2
  •  1
  •   Anthony Pegram    14 年前
    var matchingApps = from myApp in myApps
                        join yourApp in yourApps
                        on myApp.Key equals yourApp.Key
                        select new { myApp, yourApp };
    
    foreach (var pair in matchingApps)
    {
        pair.myApp.Description = pair.yourApp.Description;
    }
    

    您的问题要求“lambda coolness”,但对于连接,我发现查询表达式语法更清晰。但是,查询的lambda版本如下所示。

    var matchingApps = myApps.Join(yourApps, myApp => myApp.Key, yourApp => yourApp.Key, (myApp, yourApp) => new { myApp, yourApp });
    
        3
  •  0
  •   Community CDub    7 年前

    如果您的应用程序类中有一个Key属性,并且您将经常执行这些类型的操作,那么您可能需要考虑使用字典而不是列表。这将允许您通过密钥快速访问应用程序。

    你可以这样做:

    foreach(var app in myApps)
    {
        Application yourApp;
        if (yourApps.TryGetValue(app.Key, out yourApp)
            yourApp.Description = app.Value.Description;
    }
    

    a join 可能是你最好的选择。

        4
  •  0
  •   VoodooChild    14 年前

            foreach (var item in myApps)
            {
                var desc = yourApps.FirstOrDefault(app => app.Key == item.Key);
                if (desc != null)
                {
                    item.description = desc.description;
                }
            }
    

    还有一个forloop在那里,所以它可能不是你想要的,但仍然是我的2美分。。。

        5
  •  0
  •   Marc    14 年前

    为什么不简单(这将创建可枚举的副本):

    myApps.Join(yourApps, 
                m => m.Key, 
                y => y.Key, 
                (m, y) => new { m, y.description })
          .ToList()
          .ForEach(c => c.m.description = c.description);