2011-11-28 1 views
0

나는이 숙제를 가지고 있는데 문제가 하나 뿐이며 그 해결책을 모른다. 우리는이 클래스를 가지고 있고, 우리는 사전 C#에서 Object 키의 소품을 얻는 방법은 무엇입니까?

가 나는 맥주가 ... 또 다른 변수 또는 메소드를 만들 musn't 사전 < 맥주 개체, INT 수입>. 그러나이 메서드는 객체가 아닌 Beer 객체의 이름 (prop) 만 가지고 있습니다.

그리고 나는이 사전

나는 단지이 아이디어가에서 맥주 객체의 이름을 얻을 수있는 방법 다른 생각을 가지고 있지 않지만,이 작동하지 않습니다.

첫 번째는 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

나쁘지 않지만 이 두 가지 가져 오기를 사용해야합니다 :'using System; using 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' 값을 얻은 후에는 null을 체크 할 수 있습니다. –

+0

사실 - OP가 항목이 있는지 또는 실제로 항목을 가져올 지 여부를 확인하려고하는지 여부는 확실하지 않았습니다. – BrokenGlass

+0

나쁘지는 않지만이 두 가지 가져 오기를 사용해야합니다. using System.Collections.Generic;'Any 및 First 메서드를 호출 할 수 없으므로 ( – blaces

관련 문제