Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update an element with a List using LINQ and C#

I have a list of objects and I'd like to update a particular member variable within one of the objects. I understand LINQ is designed for query and not meant to update lists of immutable data. What would be the best way to accomplish this? I do not need to use LINQ for the solution if it is not most efficient.

Would creating an Update extension method work? If so how would I go about doing that?

EXAMPLE:
(from trade in CrudeBalancedList
 where trade.Date.Month == monthIndex
 select trade).Update(
 trade => trade.Buy += optionQty);
like image 646
Addie Avatar asked Mar 15 '10 18:03

Addie


2 Answers

Although linq is not meant to update lists of immutable data, it is very handy for getting the items that you want to update. I think for you this would be:

(from trade in CrudeBalancedList
    where trade.Date.Month == monthIndex
    select trade).ToList().ForEach( trade => trade.Buy += optionQty);
like image 169
Patrick Karcher Avatar answered Sep 19 '22 20:09

Patrick Karcher


I'm not sure if this is the best way, but will allow you to update an element from the list.

The test object:

 public class SomeClass {
        public int Value { get; set; }
        public DateTime Date { get; set; }
    }

The extension method:

public static class Extension {
        public static void Update<T>(this T item, Action<T> updateAction) {
            updateAction(item);
        }
    }

The test:

public void Test()
{
    // test data
    List<SomeClass> list = new List<SomeClass>()
    {
        new SomeClass {Value = 1, Date = DateTime.Now.AddDays(-1)},
        new SomeClass {Value = 2, Date = DateTime.Now },
        new SomeClass {Value = 3, Date = DateTime.Now.AddDays(1)}
    };
    // query and update
    (from i in list where i.Date.Day.Equals(DateTime.Now.Day) select i).First().Update(v => v.Value += 5);

    foreach (SomeClass s in list) {
        Console.WriteLine(s.Value);
    }
}
like image 25
Fernando Avatar answered Sep 21 '22 20:09

Fernando