Extension method for UPDATE in Linq to Objects

依然范特西╮ 提交于 2019-12-02 10:31:48

问题


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.


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

    }


}



回答2:


Or you could use an extension method that comes with the .Net framework:

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



回答3:


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


来源:https://stackoverflow.com/questions/1344140/extension-method-for-update-in-linq-to-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!