[c#] conditional Updating a list using LINQ

I had a list

List<Myclass> li = new List<Myclass>();

where Myclass is

class Myclass
{
public string name {get;set;}
public decimal age {get;set;}
}

items in li looks like

enter image description here

 i want to update `li` according to name but with `LINQ` like

li.where(w=> w.name = "di") = li.Where(w => w.name =="di").select(s => {s.age = 10;return s;}).Tolist();
li.where(w=> w.name = "marks") = li.Where(w => w.name =="marks").select(s => {s.age = 20;return s;}).Tolist();
li.where(w=> w.name = "grade") = li.Where(w => w.name =="grade").select(s => {s.age = 10;return s;}).Tolist();

and want result which looks like this

enter image description here

my code gives error can you please tell how i do this

This question is related to c# linq list

The answer is


How about

(from k in myList
 where k.id > 35
 select k).ToList().ForEach(k => k.Name = "Banana");

Try Parallel for longer lists:

Parallel.ForEach(li.Where(f => f.name == "di"), l => l.age = 10);

        li.Where(w => w.name == "di" )
          .Select(s => { s.age = 10; return s; })
          .ToList();

You need:

li.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);

Program code:

namespace Test
{
    class Program
    {
        class Myclass
        {
            public string name { get; set; }
            public decimal age { get; set; }
        }

        static void Main(string[] args)
        {
            var list = new List<Myclass> { new Myclass{name = "di", age = 0}, new Myclass{name = "marks", age = 0}, new Myclass{name = "grade", age = 0}};
            list.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);
            list.ForEach(i => Console.WriteLine(i.name + ":" + i.age));
        }
    }
}

Output:

 di:10
 marks:0
 grade:0

Try this:

li.ForEach(x => x.age = (x.name == "di") ?
                10 : (x.name == "marks") ?
                20 : (x.name == "grade") ?
                30 : 0 );

All values are updated in one line of code and you browse the List only ONE time. You have also a way to set a default value.


If you really want to use linq, you can do something like this

li= (from tl in li
    select new Myclass
    {
        name = tl.name,
        age = (tl.name == "di" ? 10 : (tl.name == "marks" ? 20 : 30))

    }).ToList();

or

li = li.Select(ex => new MyClass { name = ex.name, age = (ex.name == "di" ? 10 : (ex.name == "marks" ? 20 : 30)) }).ToList();

This assumes that there are only 3 types of name. I would externalize that part into a function to make it more manageable.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>