使用LINQ计算集合中的单词

时间:2010-06-11 22:10:23

标签: c# .net linq .net-3.5

我有一个StringCollection对象,其中包含5个单词。其中3个是重复的单词。我正在尝试创建一个LINQ查询,该查询将计算集合中有多少个唯一单词并将它们输出到控制台。所以,例如,如果我的StringCollection有'House','Car','House','Dog','Cat',那么它应该像这样输出:

House --> 2
Car --> 1
Dog --> 1
Cat --> 1

有关如何创建LINQ查询的任何想法吗?

7 个答案:

答案 0 :(得分:11)

尝试以下

var res = from word in col.Cast<string>()
          group word by word into g
          select new { Word = g.Key, Count = g.Count() };

答案 1 :(得分:4)

var xs = new StringCollection { "House", "Car", "House", "Dog", "Cat" };

foreach (var g in xs.Cast<string>()
                    .GroupBy(x => x, StringComparer.CurrentCultureIgnoreCase))
{
    Console.WriteLine("{0}: {1}", g.Key, g.Count());
}

答案 2 :(得分:1)

鉴于您正在使用StringCollection并希望忽略大小写,您需要将Enumerable.GroupByEnumerable.Cast一起使用:

var results = collection.Cast<string>.GroupBy(
        i => i,
        (word, words) => new { Word = word, Count = words.Count() },
        StringComparer.CurrentCultureIgnoreCase
    );

foreach(var wordPair in results)
     Console.WriteLine("Word: \"{0}\" - Count: {1}", wordPair.Word, wordPair.Count);

答案 3 :(得分:1)

构建单个字符串值结果...

var stringCollection = new[] { "House", "Car", "house", "Dog", "Cat" };
var result = stringCollection.Cast<string>().GroupBy(
                                  k => k, 
                                  StringComparer.InvariantCultureIgnoreCase)
                             .Select(v => v.Key + " -->" + v.Count())
                             .Aggregate((l,r)=>l+" " + r);
//result = "House -->2 Car -->1 Dog -->1 Cat -->1"

将每个值放在不同的行上......

var stringCollection = new[] { "House", "Car", "house", "Dog", "Cat" };
var result = stringCollection.Cast<string>().GroupBy(
                                  k => k, 
                                  StringComparer.InvariantCultureIgnoreCase);

foreach (var value in result)
    Console.WriteLine("{0} --> {1}", value.Key, value.Count());

答案 4 :(得分:0)

foreach(var g in input.GroupBy(i => i.ToLower()).Select(i => new {Word = i.Key, Count = i.Count()})
{
  Console.WriteLine(string.Format("{0} -> {1}", g.Word, g.Count));
}

答案 5 :(得分:0)

应该如此简单:

Console.WriteLine(stringCollection.Distinct().Count());

答案 6 :(得分:0)

var query =    
  from s in Collection  
  group s by s.Description into g  
  select new {word = g.Key, num = g.Count()};