Reputation:
I'm seeing a lot of select statements with return statements in them and Im confused of what is going on when an object is being returned from within a select statement. Can someone please explain?
var results = swimEntries
.Select(se =>
{
if (se.Tag == "DM+" || se.Tag == "DM-")
{
var modelEntry =
modelEntries.Find(e => e.Tag == se.Tag);
return modelEntry;
}
return se;
})
.ToList();
Upvotes: 1
Views: 1269
Reputation: 22038
What you see here is a Statement lambda. The Select()
will call for each item the code in it's body. When the se.Tag
meets some criteria, it will search for an object in the modelEntries.
You could write this statement also as:
var results = new List<ModelEntry>(); // <-- i don't know the exact type.. (wild guess)
foreach(var se in swimEntries)
{
if (se.Tag == "DM+" || se.Tag == "DM-")
{
var modelEntry = modelEntries.Find(e => e.Tag == se.Tag);
results.Add(modelEntry);
}
else
results.Add(se);
}
or if you want to keep the Select statement, you could store the body into a separate function:
private ModelEntry SearchForSomething(ModelEntry se)
{
if (se.Tag == "DM+" || se.Tag == "DM-")
{
var modelEntry = modelEntries.Find(e => e.Tag == se.Tag);
return modelEntry;
}
return se;
}
var results = swimEntries.Select(SearchForSomething).ToList();
Upvotes: 2