开发者

Setting a property from one collection to another collection

I have two colluections

List<Application>  myApps;

List<Application> yourApps;

These lists have overlapping overlapping data but they are coming from different sources and each source has some missing field data.

Application object has a property called Description

Both collections have a unique field called Key

i want to see if there is a LINQ solution to:

Loop through all applications in myApps and look at the key and see if that existing in yourApps. If it does, i w开发者_开发知识库ant to take the description property from that application in yourApps and set the description property on the application on myApps to that same value

i wanted to see if there was any slick way using lambda expressions (instead of having to have loops and a number of if statements.)


You can use a join:

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;
}


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;
}

Your question asked for "lambda coolness," but for joins, I find query expression syntax much clearer. However, the lambda version of the query is below.

Lambda version:

var matchingApps = myApps.Join(yourApps, myApp => myApp.Key, yourApp => yourApp.Key, (myApp, yourApp) => new { myApp, yourApp });


If you have a Key property in your Application class, and you'll be doing these types of operations frequently, you may want to consider using a Dictionary instead of a List. This would allow you to access the Applications quickly by key.

You could then do:

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

Otherwise, a join is probably your best option.


I think:

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

there is still a forloop in there so it might not be what you wanting, but still my 2 cents...

:)


Why not simply (this will create a copy of the enumerable):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜