2

I have an IEnumerable list, IEnumerable<SortElement> sorts;

I am updating its property as:

sorts.Where(a => a.DisplayName.ToLower() == "abc")
    .ToList()
    .ForEach(sl => sl.DisplayName = "Testing");

But it does not change the property for that specific element.

csharp coder
  • 19
  • 2
  • 4

3 Answers3

6

Change "ABC" to "abc". Your condition will never be met. You can also change .ToLower() to .ToUpper().

I would do some thing like this:

foreach(var e in sorts.Where(a => a.DisplayName.ToLower() == "abc"))
   e.DisplayName = "Testing";

Because your code in fact executes 2 loops, that's not necessary.

King King
  • 61,710
  • 16
  • 105
  • 130
3

LINQ is better for querying, it is not a good option for modification.

You can modify the list items like:

foreach (var item in sorts)
{
    if (item.DisplayName.Equals("abc", StringComparison.InvariantCultureIgnoreCase))
    {
        item.DisplayName = "Testing";
    }
}

OR

foreach (var item in 
    sorts.Where(r=> r.DisplayName.Equals("abc", StringComparison.InvariantCultureIgnoreCase)))
{
        item.DisplayName = "Testing";
}

Use string.Equals overload for case insenstive comparison.

There is one pure LINQ way of doing it but please don't. LINQ is for querying, not for modification. It should only work if SortElement is a class, not a struct, because of reference type passed to lambda.

sorts.Select(r => r.DisplayName.Equals("abc", StringComparison.InvariantCultureIgnoreCase)
                ? r.DisplayName = "Testing"
                : r.DisplayName ).ToList();

The above would work, even without assigning the result back to sorts. But it should be avoided.

Habib
  • 219,104
  • 29
  • 407
  • 436
0

You can achieve this using in place update - Select and ToList in conjuction.

In Select change the filtered list to desired value and do ToList in order to evaluate the select immediately due to lazy evaluation -

sorts.Where(a => a.DisplayName.ToUpper() == "ABC")
    .Select(sl => sl.DisplayName = "Testing").ToList();
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • This will create a new list with only those elements which are selected from the criteria. OP is looking for modification in original list. – Habib Sep 24 '13 at 17:32
  • This will indeed modify the original list. Have you give it a try? In `Select` query i update the displayName in case you missed it. – Rohit Vats Sep 24 '13 at 17:32
  • you are right. This will modify the original list, since reference will be modified later. – Habib Sep 24 '13 at 17:38
  • But I have been [downvoted for similar response](http://stackoverflow.com/questions/16191342/is-it-possible-to-do-list-manipulation-using-linq/16191448#16191448) :). – Habib Sep 24 '13 at 17:43