使用list <object> items </object>填充组合框

时间:2013-09-02 19:40:56

标签: c# list combobox

所以我创建了这个类来获取给定字符串的频率:来自List的性别 - &gt;

public static List<GenderFrequency> GenderFrequencies(List<Bird> birds)
{
    List<GenderFrequency> result = new List<GenderFrequency>();
    foreach (Bird b in birds)
        UpdateGenderList(b, result);
    return result;
}

private static void UpdateGenderList(Bird b, List<GenderFrequency> freqs)
{
    foreach (GenderFrequency freq in freqs)
        if (freq.Gender.Equals(b.Gender, StringComparison.CurrentCultureIgnoreCase))
        {
            freq.FrequencyPlus1();
            return;
        }
    GenderFrequency newfr = new GenderFrequency() { Gender = b.Gender, Frequency = 1 };
    freqs.Add(newfr);
    //Console.WriteLine(newfr);

}

private void FrequencyPlus1()
{
    Frequency = Frequency + 1;
}
public override string ToString()
{
    return Gender + " (" + Frequency + ")";
}

我想用这种方法将这些结果放在一个组合框中:

 private void showGenderFreq()
        {
            cboGenderFreq.Items.Clear();
            foreach (GenderFrequency g in GenderFrequency.GenderFrequencies())
            {
                cboGenderFreq.Items.Add(g);
            }

        }

但是它给了我一个错误,因为我不知道将什么列表参数放入Genderfrequencies()以使其工作,VS然后sugested将此代码添加到我的Genderfrequency类:

 internal static IEnumerable<GenderFrequency> GenderFrequencies()
    {
        throw new NotImplementedException();
    }

但我不认为这有多大帮助,问题可能出在showGenderFreq()的某个地方

提前谢谢

1 个答案:

答案 0 :(得分:0)

您的GenderFrequencies方法被定义为需要参数(List<Bird>),而您不提供该参数。您需要提供参数:

foreach (GenderFrequency g in GenderFrequency.GenderFrequencies(birds))

其中birds将是(理论上)定义的List<Bird>对象。

但是,我会在GenderFrequencies中从临时变量中获取List,然后遍历该临时变量,而不是每次循环调用GenderFrequencies。像这样:

List<GenderFrequency> genderFrequencies = GenderFrequencies.GenderFrequencies(birds);

foreach (GenderFrequency g in genderFrequencies)
{

}

另外,为了便于阅读,我会对您的程序进行一些小的更改。

首先,将静态GenderFrequencies方法更改为GetGenderFrequencies。它更具描述性(在我看来)。

其次,GenderFrequencyPlus1方法可以替换为简单的Frequency++;

所以看起来像这样:

foreach (GenderFrequency freq in freqs)
{
    if (freq.Gender.Equals(b.Gender, StringComparison.CurrentCultureIgnoreCase))
    {
        freq.Frequency++;
        return;
    }
}