c# - 根据键获取列表List<T>中的自定义对象T

标签 c# asp.net

我有一个列表,我称之为 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/

相关文章:

c# - Windows 中的唯一文件标识符

c# - 正则表达式正确拆分

c# - 将 ASP.net Identity 2.0 连接到现有数据库

javascript - 如何在asp.net中单击按钮下载html文件?

asp.net - 有什么好的视频聊天 API 可以集成到 ASP .NET MVC 2 Web 应用程序中吗?

asp.net - 读取 Gedcom 文件并存储在数据库中

c# - 如何解决Operator '!=' cannot be applyed to operands of type 'T' and 'T'

c# - 等待 Task.Run 与等待

javascript - 将空数组发送到 webapi

javascript - 未从 ajax post 调用 Web 方法