2011-11-28 60 views
0

我有这个功课,我只有1个问题,我不知道解决方案。我们有这个类,我们musn't创建另一个变量或方法...如何获取字典C#中的对象键的支持?

我有一个啤酒字典<啤酒对象,诠释收入>。但是该方法只获得了Beer对象的名称(prop),而不是对象。

而且我没有其他想法,我怎么可以从字典

我只有2个想法得到了啤酒对象的名称,但这些不工作。

第一个是我尝试使用一个ContainsKey()方法。第二个是的foreach迭代

using System; 
using System.Collections.Generic; 

namespace PubBeer 
{ 
    public class Beer 
    { 
     string name; 
     int price; 
     double alcohol; 


     public string Name{ get { return name; } } 

     public int Price{ get; set; } 

     public double Alcohol{ get { return alcohol;} } 

     public Sör(string name, int price, double alcohol) 
     { 
      this.name= name; 
      this.price= price; 
      this.alcohol= alcohol; 
     } 


     public override bool Equals(object obj) 
     { 
      if (obj is Beer) 
      { 
       Beer other = (Beer)obj; 
       return this.name== other.name; 
      } 
      return false; 
     } 
    } 

    public class Pub 
    { 

     int income; 

     IDictionary<Beer, int> beers= new Dictionary<Beer, int>(); 


     public int Income{ get; set; } 


     public int Sold(string beerName, int mug) 
     { 
      // Here the problem 

      beers; // Here I want to like this: beers.Contains(beerName) 
        // beers.ContainsKey(Object.Name==beerName) or someone like this 

      // foreach (var item in beers) 
      // { 
      //  item.Key.Name== beerName; 
      // } 


     } 
... 
+2

我可以建议改变你的关键。通过(可能)搜索字典中的每个关键字可以破坏字典的效率。 –

+0

@my你确实是对的,但如果这是他的家庭作业,他的老师可能希望他学习一些东西(linq查询也许?) – fnurglewitz

+0

我不认为linq ...因为他没有谈论linq-s唯一的接口在最后一课......但这是作业 – blaces

回答

2

使用LINQ查询在按键的集合。

//Throws an error if none or more than one object has the same name. 
var beer = beers.Keys.Single(b => b.Name == beerName); 

beers[beer] = ...; 

// -or - 

//Selects the first of many objects that have the same name. 
//Exception if there aren't any matches. 
var beer = beers.Keys.First(b => b.Name == beerName); 

beers[beer] = ...; 

// -or - 

//Selects the first or default of many objects. 
var beer = beers.Keys.FirstOrDefault(b => b.Name == beerName); 

//You'll need to null check 
if (beer != null) 
{ 
    beers[beer] = ...; 
} 

// etc... 

更新:NON-LINQ替代

Beer myBeer; 

foreach (var beer in beers.Keys) 
{ 
    if (beer.Name == beerName) 
    { 
     myBeer = beer; 
     break; 
    } 
} 

if (myBeer != null) 
{ 
    beers[myBeer] = ...; 
} 
+0

这并不坏,但我必须使用这两个导入:'使用System; 使用System.Collections.Generic;' – blaces

0

尝试使用键的属性

beers.Keys.Where(p => p.name == beername) 

beers.Keys.FirstOrDefault(p => p.name == beername) 
1

你可以在领取钥匙使用Any()

if (beers.Keys.Any(x => x.Name == beerName)) 
{ 
} 

在这是最糟糕的情况必须查看所有啤酒 - 如果您通常按名称查啤酒,则应考虑将啤酒名称作为关键字,啤酒对象本身就是字典中的价值。

一旦你已经确定了这样的啤酒存在,你可以使用First()选择它:

Beer myBeer = beers.First(x => x.Key.Name == beerName).Key; 
+0

'FirstOrDefault'比'Any' +'First'更有效率。返回“myBeer”值后,您可以进行空检查。 –

+0

true - 我不确定OP是否想要检查项目是否存在,或者实际上是否获得项目 – BrokenGlass

+0

这并不坏,但我必须使用这两个导入:'using System; using System.Collections.Generic;'所以我不能调用任何和第一种方法:( – blaces