2015-12-11 95 views
1

我有我称之为Actions看起来像这样基于关键

public class Actions 
{ 
     public string Type { get; set; } 
     public string Observations { get; set; } 

     public Actions(
      string type, 
      string observations) 
     { 
      Type = type; 
      observations= type; 
     } 
} 

列表列表列表 获取自定义对象T,那我后来在一个列表中使用像 List<Actions> data= new List<Actions>();

此列表将持有各种鸟类,以及他们观察到的时间。这些数据来自我逐一阅读的文件。因此,在一个循环内,我可能会发现Eagle, 1,这意味着我必须在该列表中找到具有type==Eagle的对象,并为其键添加+1。

我可以遍历这个列表当然,并检查它的i th对象的type键,有我想要的值,并增加它的observations

有没有人知道我做了什么后更好的方式?

回答

4

我可以迭代这个列表当然,并检查它的第i个对象的类型键,有我想要的值,并增加它的观察值。

是的,这将工作。

你会做这样的:

var birdToUpdate = birdList.FirstOrDefault(b => b.Type == keyToFind); 
if (birdToUpdate == null) 
{ 
    birdToUpdate = new Actions(keyToFind, 0); 
    birdList.Add(birdToUpdate); 
} 
birdToUpdate.Observations++; 

如果返回None,这对于那些鸟先观察,所以你添加它。

再后来,如果你想添加颜色到搭配:

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++; 

另一个办法是放弃这个类entirey并引入Dictionary<string, int>其中关键是鸟的名称和int观察的数量。

或者,如果你坚持使用这个课程,那么请为该课程考虑一个合适的名称并使其成为Dictionary<string, Actions>

伪:

Actions actionForBird; 

if (!dictionary.TryGetValue(keyToFind, out actionForBird)) 
{ 
    actionForBird = new Actions(keyToFind, 0); 
    dictionary[keyToFind] = actionForBird; 
} 

actionForBird.Observations++; 
+0

其实起初我有完全相同的事情你建议使用我的数据字典。但不幸的是,我不能将它改成字典,因为只是现在我只需要担心观察,很快我可能不得不担心颜色,位置等等。所以我必须转储字典,然后不能使用'TryGetValue'了。 – dearn44

+0

如果我使用多个词典,每个可能的关键词之一(例如观察),直到我形成我的数据,然后当每个变量准备好在自己的词典中时,我可以将它们合并到最终的对象中? – dearn44

+0

我在查看'FirstOrDefault()'如何解决我的问题时遇到困难? – dearn44

0

请尝试使用字典

lambda表达式

例如

var type = 'eagle'; 
Dictionary<string, int> observations = new Dictionary<string, int>(); 
var obj = observations.FirstOrDefault(p => p.Key == type); 

把用户输入到var type

+0

为什么使用字典,如果你要遍历所有密钥('FirstOrDefault')? – CodeCaster

+0

不幸的是,现在不可能改变数据类型。 – dearn44

+0

使用字典的关键在于它包含一个散列表,它通过键(O(1))操作来检索值。你正在迭代字典,这可能是一个O(n)(更糟糕的)。 –