2011-11-28 25 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

相關問題