我有一个列表,我称之为 Actions
看起来像这样
public class Actions
{
public string Type { get; set; }
public string Observations { get; set; }
public Actions(
string type,
string observations)
{
Type = type;
observations= type;
}
}
我稍后会在像 List<Actions> data= new List<Actions>();
这样的列表中使用
此列表将包含鸟类的类型以及观察它们的时间。这个数据来 self 一个一个读取的文件。所以在循环中,我可能会找到 Eagle, 1
这意味着我必须在该列表中找到具有 type==Eagle
的对象并将 +1 添加到其 observations
key 。
我当然可以遍历这个列表并检查它是否是 i
第对象的 type
键,具有我想要的值并将其递增为 observations
.
有谁知道更好的方法来实现我所追求的目标?
最佳答案
I can iterate over this list of course and check if its ith object's type key, has the value that I want and increment it's observations.
是的,那行得通。
你会这样做:
var birdToUpdate = birdList.FirstOrDefault(b => b.Type == keyToFind);
if (birdToUpdate == null)
{
birdToUpdate = new Actions(keyToFind, 0);
birdList.Add(birdToUpdate);
}
birdToUpdate.Observations++;
如果没有返回,则这是该鸟的第一次观察,因此您添加它。
然后,如果您想在混合中添加颜色:
var birdToUpdate = birdList.FirstOrDefault(b => b.Type == keyToFind
&& b.Color == colorToFind);
if (birdToUpdate == null)
{
birdToUpdate = new Actions(keyToFind, colorToFind, 0);
birdList.Add(birdToUpdate);
}
birdToUpdate.Observations++;
另一种方法是完全转储这个类并引入一个 Dictionary<string, int>
其中键是鸟的名字,整数是观察次数。
或者,如果你坚持使用这个类,那么请为这个类想一个合适的名字,让它成为Dictionary<string, Actions>
。 .
伪:
Actions actionForBird;
if (!dictionary.TryGetValue(keyToFind, out actionForBird))
{
actionForBird = new Actions(keyToFind, 0);
dictionary[keyToFind] = actionForBird;
}
actionForBird.Observations++;
关于c# - 根据键获取列表List<T>中的自定义对象T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34225610/