Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update property or create new element if it does not exist Lambda c#

Tags:

c#

.net

lambda

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 =)

like image 333
afreeland Avatar asked Jan 12 '23 23:01

afreeland


1 Answers

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.

like image 63
Sergey Berezovskiy Avatar answered Jan 29 '23 15:01

Sergey Berezovskiy