开发者

How to get count similar word in list?

I have C# list with lot of similar name i want to count all individual similar word.

Example

Suppose list has these values

one,one,one,two,two,four,four,four

then i want to calculate like 开发者_开发知识库this

one 3
two 2
four 3 

how can i calculate value like this from list.


I would split the string on comma, loop through all the results and add each word to a hashtable or dictionary with a value of one. If the word (key) is already present, then increment the value.

string[] values = "one,one,one,two,two,four,four,four".Split(',');
var counts = new Dictionary<string, int>();

foreach (string value in values) {
    if (counts.ContainsKey(value))
        counts[value] = counts[value] + 1;
    else 
        counts.Add(value, 1);
}

Or, if you prefer, here is a LINQ solution

var counts = values.GroupBy<string, string, int>(k => k, e => 1)  
   .Select(f => new KeyValuePair<string, int>(f.Key, f.Sum()))   
   .ToDictionary(k => k.Key, e => e.Value);  


Here is a solution based on Linq:

    string s = "one,one,one,two,two,four,four,four";
    List<string> list = s.Split(',').ToList();

    Dictionary<string, int> dictionary = list.GroupBy(x => x)
        .ToDictionary(x => x.Key, x => x.Count());

    foreach (var kvp in dictionary)
        Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);

Output:

one: 3
two: 2
four: 3

This solutions doesn't take advantage of the fact that the common values are consecutive. If this is always the case, a slightly faster solution could be written, but this is fine for short lists, or if the items can come in any order.


Dictionaty<string, int> listCount = new Dictionaty<string, int>();
for (int i = 0; i < yourList.Count; i++)
{
 if(listCount.ContainsKey(yourList[i]))
  listCount[yourList[i].Trim()] = listCount[yourList[i].Trim()] + 1;
 else
  listCount[yourList[i].Trim()] = 1;
}


For List, you could do the following (untested):

List<string> list = new List<string>()
  {
    "One",
    "One",
    "Two",
    // etc
  }

Dictionary<string, int> d = new Dictionary<string, int>();

foreach (string s in list)
{
  if (d.ContainsKey(s))
    d.Add(s, 1);
  else
    d[s]++;
}

The preferred (and cleaner) method is to do this using GroupBy and Count with Linq, but I don't have the type to type out the syntax at the moment.

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜