C# 更新通用列表中元素的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19280986/
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
Best way to update an element in a generic List
提问by John H.
Suppose we have a class called Dog with two strings "Name" and "Id". Now suppose we have a list with 4 dogs in it. If you wanted to change the name of the Dog with the "Id" of "2" what would be the best way to do it?
假设我们有一个名为 Dog 的类,其中包含两个字符串“Name”和“Id”。现在假设我们有一个包含 4 只狗的列表。如果你想用“2”的“Id”更改狗的名字,最好的方法是什么?
Dog d1 = new Dog("Fluffy", "1");
Dog d2 = new Dog("Rex", "2");
Dog d3 = new Dog("Luna", "3");
Dog d4 = new Dog("Willie", "4");
List<Dog> AllDogs = new List<Dog>()
AllDogs.Add(d1);
AllDogs.Add(d2);
AllDogs.Add(d3);
AllDogs.Add(d4);
采纳答案by Mike Perrenoud
AllDogs.First(d => d.Id == "2").Name = "some value";
However, a safer version of that might be this:
但是,更安全的版本可能是这样的:
var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }
回答by gleng
You could do:
你可以这样做:
var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));
This will return the matching dog, else it will return null
.
这将返回匹配的狗,否则将返回null
。
You can then set the property like follows:
然后,您可以按如下方式设置属性:
if (matchingDog != null)
matchingDog.Name = "New Dog Name";
回答by gleng
If the list is sorted (as happens to be in the example) a binary search on index certainly works.
如果列表已排序(就像示例中那样),则对索引的二分搜索肯定有效。
public static Dog Find(List<Dog> AllDogs, string Id)
{
int p = 0;
int n = AllDogs.Count;
while (true)
{
int m = (n + p) / 2;
Dog d = AllDogs[m];
int r = string.Compare(Id, d.Id);
if (r == 0)
return d;
if (m == p)
return null;
if (r < 0)
n = m;
if (r > 0)
p = m;
}
}
Not sure what the LINQ version of this would be.
不确定它的 LINQ 版本是什么。