我不確定這是否是最好的方法,但可以讓您更新列表中的元素。
測試對象:
public class SomeClass {
public int Value { get; set; }
public DateTime Date { get; set; }
}
擴展方法:
public static class Extension {
public static void Update<T>(this T item, Action<T> updateAction) {
updateAction(item);
}
}
測試:
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);
}
}
我看到這個條目,並認爲鏈接到這將是適用於任何希望我的問題。 http://stackoverflow.com/questions/1344140/extension-method-for-up-date-in-linq-to-objects – Addie 2010-03-16 00:45:56