本文介绍了使用Linq在C#中进行列表操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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来更新列表.

How can I update the list by replacing the honda car of Id 1 with honda car with Id 3 in the best way.

推荐答案

所有嬉皮士说-加:

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>.

This just uses the existing FindIndex to locate a car with id 1, then replace or add it. No LINQ; no SQL - just a lambda and List<T>.

这篇关于使用Linq在C#中进行列表操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 11:57
查看更多