为UPDATE在LINQ到对象扩展方法(Extension method for UPDATE in

2019-08-02 21:20发布

在下列情况下,我查询列表对象和匹配的谓词我要更新一些值:

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

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

我的目标是只更新我的列表中的项目相匹配而使其他物品完好状态这。

Answer 1:

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

    }


}


Answer 2:

或者你可以使用自带的.net框架的扩展方法:

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


Answer 3:

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


文章来源: Extension method for UPDATE in Linq to Objects