List Manipulation in C# using Linq

后端 未结 8 536
庸人自扰
庸人自扰 2020-12-24 12:24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ConsoleApplication1
{

    public cla         


        
相关标签:
8条回答
  • 2020-12-24 13:11

    As Leppie said, LINQ is for querying rather than updating. However, that can be used to build a new list:

    mylist = new List<Car>(from car in mylist select car.id == 1? car3 : car)
    

    That is if you want to use LINQ. It's nice and short code, of course, but a bit less efficient than Marc Gravell's suggestion, as it effectively creates a new list, rather than updating the old one.

    0 讨论(0)
  • 2020-12-24 13:13

    You can use this way :

    (from car in mylist
    where car.id == 1
    select car).Update(
    car => car.id = 3);
    

    My reference is this website. Or following is the code for Update method

    public static void Update<T>(this IEnumerable<T> source, params Action<T>[] updates)
    {
        if (source == null)
            throw new ArgumentNullException("source");
    
        if (updates == null)
            throw new ArgumentNullException("updates");
    
        foreach (T item in source)
        {
            foreach (Action<T> update in updates)
            {
                update(item);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题