Skip to main content
 首页 » 编程设计

c#之根据键获取列表ListT>中的自定义对象T

2024年02月05日14shangdawei

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