I have a large List<> of Name/Value pairs and need to be able to find if a particular Name exist in this list...if so update that Value, if NOT then create a new Name/Value pair and append it to my List.
What is the Lambda syntax to do this?
I have tried using .Where .DefaultIfEmpty but it just returns an empty object but does not append it to my original 'myList'
myList.Where(x => x.Name == 'some name').DefaultIfEmpty(new myobj(){ Name = 'some name').First().Value = 'some value';
I have to do this four multiple Names so if I had a simple syntax that would make it great =)
You can use this extension method:
public static void UpdateOrAdd(this List<myobj> source,
string name, object value)
{
var obj = source.FirstOrDefault(x => x.Name == name);
if (obj == null)
{
obj = new myobj { Name = name };
source.Add(obj);
}
obj.Value = value;
}
Usage:
myList.UpdateOrAdd("some name", "some value");
But consider to use dictionary, as @Sam suggested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With