0

我在字典中有以下代码

SN00001002001
SN00001002002
SN00001002003
SN00001002004
 ...
AN00001002006
AN00001002007
AN00001002008. 

我想将其显示为

SN00001002 001-006  6(count)
AN00001002 001-008  8(count)

我使用了以下代码

Dictionary<object, int> counts = new Dictionary<object, int>();

            foreach (string item in str1)
            { 
               if (!counts.ContainsKey(item1))
                    {
                        counts.Add(item1, 1);                           
                   }                    }
                else
                {
                    counts[item]++;                        
                }
            }

它正确显示计数为

SN00001002   6(count)
AN00001002   8(count)

,但不是序列号。任何人都可以为此提出一个想法。

4

1 回答 1

2

试试这个...

var serialNumbers = from sn in str1 
        group sn by sn.Substring(0, 10) into g
        select new { 
                         Key = g.Key, 
                         Cnt = g.Count(), 
                         Min = g.Min(v => v.Substring(10)), 
                         Max = g.Max(v => v.Substring(10))
                     };

foreach (var sn in serialNumbers)
{
    Console.WriteLine("{0} {1}-{2} {3}(count)", sn.Key, sn.Min, sn.Max, sn.Cnt);
}

这是我上面用来测试的代码(来自 LinqPad)

List<string> str1 = new List<string>();
str1.Add("SN00001002001");
str1.Add("SN00001002002");
str1.Add("SN00001002003");
str1.Add("SN00001002004");
str1.Add("SN00001002005");
str1.Add("SN00001002006");
str1.Add("AN00001002001");
str1.Add("AN00001002002");
str1.Add("AN00001002003");
str1.Add("AN00001002004");
str1.Add("AN00001002005");
str1.Add("AN00001002006");
str1.Add("AN00001002007");
str1.Add("AN00001002008");

var serialNumbers = from sn in str1 
    group sn by sn.Substring(0, 10) into g
    select new { Key = g.Key, Cnt = g.Count(), Min = g.Min(v => v.Substring(10)), Max = g.Max(v => v.Substring(10))};

foreach (var sn in serialNumbers)
{
    string serialNumber = string.Format("{0} {1}-{2} {3}(count)", sn.Key, sn.Min, sn.Max, sn.Cnt); 
    serialNumber.Dump();
}

输出是...

SN00001002 001-006 6(count)
AN00001002 001-008 8(count)
于 2012-08-27T12:40:43.847 回答