-1

Why it's unable to update item value based on a condition using LINQ Here is my code :

class Program
{
    public static List<Items> items = new List<Items>();
    static void Main(string[] args)
    {


        // Add items to list
        for (int i = 65; i <= 70 ; i++)
        {
        var RowItem = new Items();
            RowItem.Code = i;
            RowItem.Char = (char)(i);
            items.Add(RowItem);
        }


        //Update item
        items
            .Where(s => s.Code == 70)
            .Select(s => { s.Char ='*' ; return s; })
            .ToList();

        Console.WriteLine("\n\n\n");
        foreach (var item in items)
        {
            Console.WriteLine("\t " + item.Code + " ----> " + item.Char);
        }

        Console.ReadKey(true);
    }
}

Item class defined as below Item class defined as below Item class defined as belowItem class defined as below

public class Items
{
    public int Code { get; set; }
    public Char Char { get; set; }
}

1 Answers1

3
    //Update item
    items
        .Where(s => s.Code == 700)
        .Select(s => { s.Char ='*' ; return s; })
        .ToList();

You do not update anything. You just create a temporary list and then discard the result, because it is not assigned to anything.

Note that Items is a value type and cannot be effected by modifying the local copy of it in the lambda function.

Marcel
  • 1,688
  • 1
  • 14
  • 25