使用Linq在C#中列出操作

Lea*_*ner 28 c# linq

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

namespace ConsoleApplication1
{

    public class Class1  
    {
       static void Main(string[] args)
       {
           List<Car> mylist = new List<Car>();
           Car car1;
           Car car2;
           Car car3;

           car1 = new Car()
           {
               make = "Honda",
               id = 1
           };
           car2 = new Car()
           {
               make = "toyota",
               id = 2
           };

           car3 = new Car()
           {
              make = "Honda",
              id = 3,
              color = "red"
           };

           mylist.Add(car1);
           mylist.Add(car2);
           **////mylist.Where(p => p.id == 1).SingleOrDefault() = car3;**
        }        
    }

    public class Car
    {
        public int id { get; set; }
        public string make { get; set; }
        public string color { get; set; }

    }
}
Run Code Online (Sandbox Code Playgroud)

如何以最好的方式将Id 1的本田汽车替换为具有Id 3的本田汽车来更新列表.

Mar*_*ell 53

莱比说的一切 - 加上:

int index = mylist.FindIndex(p => p.id == 1);
if(index<0) {
    mylist.Add(car3);
} else {
    mylist[index] = car3;
}
Run Code Online (Sandbox Code Playgroud)

这只是使用现有的FindIndex来定位id为1的汽车,然后替换或添加它.没有LINQ; 没有SQL - 只是一个lambda和List<T>.


Joe*_*dor 9

如果你想对多个元素进行更新......

foreach (var f in mylist.FindAll(x => x.id == 1))  
{    
    f.id = car3.id;  
    f.color = car3.color;  
    f.make = car3.make;  
}  
Run Code Online (Sandbox Code Playgroud)


lep*_*pie 8

这不是LINQ2SQL.

此外,LINQ不用于更新,仅用于查询对象.


Fun*_*y81 6

你可以这样使用:

(from car in mylist
where car.id == 1
select car).Update(
car => car.id = 3);
Run Code Online (Sandbox Code Playgroud)

我的参考是这个网站.或者以下是Update方法的代码

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)