I’m trying to find the best way to update an object which could be in one out of a handful of different list / collections
Example:
public class MyItem
{
public Guid Id { get; set; }
public string Name { get; private set; }
public string Status { get; private set; }
public MyItem(string name)
{
this.Id = new Guid();
this.Name = name;
}
public void UpdateStatus(string status)
{
this.Status = status;
}
}
public class OtherClass
{
public ObservableCollection<MyItem> ItemList1;
public ObservableCollection<MyItem> ItemList2;
public ObservableCollection<MyItem> ItemList3;
public UpdateStatus(Guid id, string status)
{
// Figure out which ItemList needs to be updated
var item = ItemList1.FirstOrDefault(s => s.Id == id);
if (item == null)
{
item = ItemList2.FirstOrDefault(s => s.Id == id);
if (item == null)
{
item = ItemList3.FirstOrDefault(s => s.Id == id);
if (item == null)
{
Debug.WriteLine("Unable to update Status");
return;
}
}
}
item.UpdateStatus(status);
}
}
I dislike the nested if’s so I’m sure there is a better way, but its Friday and my brain is fried 🙁
I realize that I could add something like this instead of the nested ifs:
public MyItem UpdatedStatus(ObservableCollection collection, Guid id)
{
return collection.FirstOrDefault(s => s.Id == id);
}
or
public bool UpdatedStatus(ObservableCollection collection, Guid id, string status)
{
var item = collection.FirstOrDefault(s => s.Id == id);
if (item != null)
{
item.UpdateStatus(status);
return true;
}
return false;
}
But it seems like there should be a better way
Any tips?
These collections could have hundreds of items in them with more in the later ones so I’m trying to find the most efficient way to handle the updates.
LINQ for help. Does it work for you as expected?
Important:
Union() returns unique elements, it could be slow on large data sets so consider using Concat() for large lists instead”
Also it worth take a look at the Jon Skeet’s
Concat()implementation from edulinq serie,Concat()is really straightforward: (Full Article)