c# - 使用 Linq 在 C# 中进行列表操作

标签 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; }

    }
}

如何以最佳方式将 Id 1 的本田汽车替换为 Id 3 的本田汽车来更新列表。

最佳答案

leppie 所说的一切 - 加上:

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

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

关于c# - 使用 Linq 在 C# 中进行列表操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/361921/

相关文章:

c# - 编码问题。我哪里错了?

c# - 在运行时指定通用集合类型参数

c# - 在 LINQ 中调用 Task<> 方法并返回数据

c# - 具有深度的递归层次连接

c# 为一组对象获取属性并确保所有对象的值相同

c# - 如何在 ASCX 上设置控件的 Int 属性?

c# - aleagpu 抛出的 TypeInitializationException

c# - 什么时候用 'if…else if'什么时候用

c# - linq搜索多列

c# - 在 Linq 查询中调用类方法