Reputation: 196711
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 want 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.)
Upvotes: 0
Views: 157
Reputation: 9354
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);
Upvotes: 0
Reputation: 887867
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;
}
Upvotes: 2
Reputation: 126932
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 });
Upvotes: 1
Reputation: 9784
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...
:)
Upvotes: 0
Reputation: 564731
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.
Upvotes: 0