Linq到对象中UPDATE的扩展方法

时间:2009-08-27 22:43:47

标签: linq-to-objects

在以下场景中,我正在查询List对象,对于匹配谓词,我想更新一些值:

var updatedList = MyList
                 .Where (c => c.listItem1 != "someValue")  
                 .Update (m => {m.someProperty = false;});

唯一的问题是没有更新扩展方法。如何解决这个问题?

我的目标是仅更新列表中符合条件的项目,其他项目保持不变。

3 个答案:

答案 0 :(得分:8)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var people = new List<Person> {
                new Person{Name="aaa", Salary=15000, isHip=false}
                ,new Person{Name="aaa", Salary=15000, isHip=false}
                ,new Person{Name="bbb", Salary=20000, isHip=false}
                ,new Person{Name="ccc", Salary=25000, isHip=false}
                ,new Person{Name="ddd", Salary=30000, isHip=false}
                ,new Person{Name="eee", Salary=35000, isHip=false}
            };


            people.Where(p => p.Salary < 25000).Update(p => p.isHip = true);

            foreach (var p in people)
            {
                Console.WriteLine("{0} - {1}", p.Name, p.isHip);
            }


        }
    }

    class Person
    {

        public string Name { get; set; }
        public double Salary { get; set; }
        public bool isHip { get; set; }
    }


    public static class LinqUpdates
    {

        public static void Update<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach (var item in source)
                action(item);
        }

    }


}

答案 1 :(得分:4)

或者您可以使用.Net框架附带的扩展方法:

var updatedList = MyList
                 .Where (c => c.listItem1 != "someValue")  
                 .ForEach(m => m.someProperty = false);

答案 2 :(得分:1)

foreach(var item in MyList.Where(c => c.listItem1 != "someValue"))
{
    item.someProperty = false;
}