I want to update two lists using a LINQ query. I have an IDictionary<>
value with ids and values. I want to update another list with relevant ids with relevant value.
public void UpdateList(IDictionary<int, int> sortOrder)
{
var current = GetList();
foreach (var item in current)
{
foreach (var i in sortOrder)
{
if (item.Id == i.Key)
{
item.SortOrder = i.Value;
}
}
}
}
I came up with this solution. but I need to do in more effective way using LINQ.
Well you can avoid nested loops by performing a dictionary lookup instead:
public void UpdateList(IDictionary<int, int> sortOrder)
{
var current = GetList();
foreach (var item in current)
{
int value;
if (sortOrder.TryGetValue(item.Id, out value))
{
item.SortOrder = value;
}
}
}
That's not using LINQ, but as LINQ is for querying rather than updating, I'm not sure how LINQ would help...
See more on this question at Stackoverflow