c#中的列表字典(似乎无法获取我的列表)

时间:2013-06-07 11:22:27

标签: c# linq list collections

在这里,我使用linq过滤数组中的结果并传入列表,然后从该列表转换为字典,如下所示

//array is a multidimensional array with string data in it 
var datumn = array;
var list = new List<string>();
var stringcounts = new Dictionary<int,List<string>>();
var listtemp = new List<string>();

//linq

var arrayresult = from string a in datumn where a != "FREE" select a;

//adding result from arrayresult to list

foreach (var listing in arrayresult)
{
    list.Add(listing);
}

//using linq again i filter my list then add to dictionary

for (int count = 3; count > 0; count-- )
{
    var duplicateItems = from x in list
                         group x by x into grouped
                         where grouped.Count() == count 
                         select grouped.Key;
    foreach (var replace in duplicateItems)
    {
        listtemp.Add(replace.ToString());
    }

    stringcounts.Add(count, lists);

    //clearing the list to avoid duplicating data in my dictionary 
    listtemp.Clear();

}

for (int key = stringcounts.Count; key > 0; --key)
{
    var holding = stringcounts[key];

    foreach (var li in holding)
    {
        MessageBox.Show(li.ToString());
        //just view what i have to check if the data is correct
    }

}

`
程序跳过列表上的迭代器和结尾可以帮助解决这个问题 我已经尝试了一切,包括linq和其他集合,如哈希表 和地图,但没有任何作用,它不是一个控制台应用程序

3 个答案:

答案 0 :(得分:7)

这一行错了:

   var dict = new Dictionary<int, List<string>>();

删除“;”。

结果:

  

靛蓝银紫紫色绿色粉红色红棕黄色

编辑:用于比较的完整代码:

   var dict = new Dictionary<int, List<string>>()
  {
 {1, new List<string>{"red", "brown", "yellow"}},
 {2, new List<string>{"purple", "green", "pink"}},
 {3, new List<string>{"indigo", "silver", "violet"}}        
  };

// now i want to get my values from the lists in the dictionary 

for (int count = 3; count > 0; count--)
{
    var l = dict[count];

    foreach (var li in l)
    {
        li.Dump();
    }
}

答案 1 :(得分:1)

foreach (var item in dict)
        {
            var list = item.Value;
            foreach (var str in list)
            {
                MessageBox.Show(str);
            }
        }

答案 2 :(得分:0)

listtemp.Clear()是一个错误的语法,因此应该将其删除,并且应该在for循环中声明listtemp,从而消除冗余和初始问题