如何在Dictionary C#中获得Object键的支柱?

时间:2011-11-28 13:33:41

标签: c# dictionary

我有这个功课,我只有一个问题,我不知道解决方案。我们有这个类,我们不会创建另一个变量或方法......

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

我没有其他想法,如何从字典中获取Beer对象的名称

我只有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;
           //  }


        }
...

3 个答案:

答案 0 :(得分: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...

更新:非LINQ替代

Beer myBeer;

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

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

答案 1 :(得分:1)

您可以在Keys集合上使用Any()

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

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

一旦确定存在这样的啤酒,您可以使用First()来选择它:

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

答案 2 :(得分:0)

尝试使用Keys属性

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

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