当前位置: 代码迷 >> C# >> 循环字典取一样的值放到一行
  详细解决方案

循环字典取一样的值放到一行

热度:374   发布时间:2016-04-28 08:41:44.0
循环字典取一样的值放到一起
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.add("合同1","10");
dic.add("合同2","10");
dic.add("合同3","10");
dic.add("合同4","20");
dic.add("合同5","20");
dic.add("合同6","30");

现在要循环遍历这个字典,最后得出值一样的合同有几个,分别是什么,如上面的数据最终得出的结论是:
值一样的合同有3个,分别是合同1,合同2,合同3
值一样的合同有2个,分别是合同4,合同5
值一样的合同有1个,分别是合同6

看看这个怎么写,谢谢了!
------解决思路----------------------
void Main()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("合同1","10");
dic.Add("合同2","10");
dic.Add("合同3","10");
dic.Add("合同4","20");
dic.Add("合同5","20");
dic.Add("合同6","30");

var query = dic.AsEnumerable().GroupBy(x=>x.Value)
   .Select(x=>new {Count=x.Count(), Details=string.Join(",", x.Select(y=>y.Key).ToArray())});

    foreach(var item in query)
Console.WriteLine("值一样的合同有{0}个,分别是{1}",item.Count,item.Details);
}

------解决思路----------------------

Dictionary<int,LIst<string>> dic_1 = new ...
foreach(var v in dic){
    if(dic_1.ContainsKey(v.Value)) dic_1[v.Value].Add(v.Key);
    else{
        List<string> lst = new ..
        lst.Add(v.Key);
        dic_1.Add(v.Value,lst);
    }
}

------解决思路----------------------
怎么说呢?如果你对于其它的自然科学课程知识知道的越多,越能理解,其实这些东西完全跟编程无关,是设计任何一种模型,都需要的概念。
------解决思路----------------------

var query = dic.GroupBy(p => p.Value).Select(p => new
{
p.Key,
n = p.Select(s => s.Key)
});

foreach(var s in query)
{
   Console.WriteLine("值为{0}的有{1}个,分别是:{2}", s.Key, s.n.Count(), string.Join(",", s.n));
}

------解决思路----------------------

Dictionary<string, Dictionary<string, string>> parameterList = new Dictionary<string, Dictionary<string, string>>();
parameterList.Add("合同1", new Dictionary<string, string>() { { "11", "22" }, { "18", "29" } });
parameterList.Add("合同2", new Dictionary<string, string>() { { "11", "22" }, { "18", "29" } });
parameterList.Add("合同3", new Dictionary<string, string>() { { "11", "22" } });
parameterList.Add("合同4", new Dictionary<string, string>() { { "11", "222" } });
parameterList.Add("合同5", new Dictionary<string, string>() { { "11", "222" } });
parameterList.Add("合同6", new Dictionary<string, string>() { { "11", "2222" } });


var query = parameterList.GroupBy(p =>string.Join("",p.Value.Select(s=>s.Key+s.Value).OrderBy(s=>s)));
foreach(var s in query)
{
   Console.WriteLine("值为{0}的有{1}个,分别是:{2}",string.Join(",", s.First().Value.Select(p=>p.Value)), s.Count(), string.Join(",",s.Select(p=>p.Key)));
}
  相关解决方案