Linq to Objects中UPDATE的扩展方法

问题描述:

在以下情况下,我要查询一个List对象,并且要匹配的谓词要更新一些值:

In the following scenario, I am querying a List object and for the matching predicate I want to update some values:

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

唯一的问题是没有更新扩展方法.该怎么办?

The only issue is there is no Update extension method. How to go about this?

我的目标是仅更新列表中与条件匹配的其他项目,而其他项目保持不变.

My objective is update only those items in my list which match the condition leaving the other items intact.

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);
        }

    }


}