使用 Linq 在 C# 中进行列表操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/361921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List Manipulation in C# using Linq
提问by Learner
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; }
}
}
How can I update the list by replacing the honda car of Id 1 with honda car with Id 3 in the best way.
如何通过以最佳方式将 ID 1 的本田汽车替换为 ID 3 的本田汽车来更新列表。
采纳答案by Marc Gravell
Everything leppie said - plus:
leppie 所说的一切 - 加上:
int index = mylist.FindIndex(p => p.id == 1);
if(index<0) {
mylist.Add(car3);
} else {
mylist[index] = car3;
}
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>
.
这只是使用现有的 FindIndex 来定位 ID 为 1 的汽车,然后替换或添加它。没有LINQ;没有 SQL - 只是一个 lambda 和List<T>
.
回答by leppie
This is not LINQ2SQL.
这不是 LINQ2SQL。
Also, LINQ is not used for updating, only to query for objects.
此外,LINQ 不用于更新,仅用于查询对象。
回答by Joel Meador
If you wanted to do an update to multiple elements...
如果您想对多个元素进行更新...
foreach (var f in mylist.FindAll(x => x.id == 1))
{
f.id = car3.id;
f.color = car3.color;
f.make = car3.make;
}
回答by Funky81
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
我的参考是这个网站。或者以下是 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);
}
}
}
回答by jalf
As Leppie said, LINQ is for querying rather than updating. However, that can be used to build a new list:
正如 Leppie 所说,LINQ 用于查询而不是更新。但是,这可用于构建新列表:
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.
也就是说,如果您想使用 LINQ。当然,这是很好且简短的代码,但比 Marc Gravell 的建议效率低一些,因为它有效地创建了一个新列表,而不是更新旧列表。
回答by rockvista
//Item class
Class Item
{
public string Name { get; set; }
}
List < Item > myList = new List< Item >()
//Add item to list
Item item = new Item();
item.Name = "Name";
myList.Add(Item);
//Find the item with the name prop
Item item2 = myList.Find(x => x.Name == "Name");
if(item2 != null)
item.Name = "Changed";
回答by JPM
Just one question, why do I have to write a Update function for something that seems so basic for a list? There should be standard methods for Lists like Add(), Delete(), Edit(), Insert(), Replace() ....Find()
只是一个问题,为什么我必须为列表中看起来如此基本的东西编写一个更新函数?列表应该有标准方法,如 Add()、Delete()、Edit()、Insert()、Replace() ....Find()
回答by jose mauricio
List<AvailabilityIssue> ai = new List<AvailabilityIssue>();
ai.AddRange(
(from a in db.CrewLicences
where
a.ValidationDate <= ((UniversalTime)todayDate.AddDays(30)).Time &&
a.ValidationDate >= ((UniversalTime)todayDate.AddDays(15)).Time
select new AvailabilityIssue()
{
crewMemberId = a.CrewMemberId,
expirationDays = 30,
Name = a.LicenceType.Name,
expirationDate = new UniversalTime(a.ValidationDate).ToString("yyyy-MM-dd"),
documentType = Controllers.rpmdataController.DocumentType.Licence
}).ToList());