How to get the re-occurrence count of an item in an IList? (Without Immutable in loop)

StackOverflow https://stackoverflow.com/questions/17070700

  •  31-05-2022
  •  | 
  •  

سؤال

Hey guys I feel like this is a pretty simple question but I cannot find the answer. I have an IList with a bunch of items in it. And I want to count how many items are duplicated(This IList will have a lot of duplicated). So if the list has 'apple' in it 20 times and 'bannana' in it 30 times I want to put those into an associative array with the name as the key and the count as the value. I am currently doing it with this....

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

        foreach (myModel.Row in model.items)
        {
            if (summary.Count == 0 || !summary.ContainsKey(row.ItemTitle))
            {
                summary.Add(row.ItemTitle, 1);
            }
            else
            {
                summary[row.ItemTitle] += 1;
            }
        }

so model.items is an IList that contains Row.

The problem with this is that in the else I am incrementing an immutable in a loop, so I know there is a better way.

Thanks in advance for the help.

edit

What I mean by no immutable in a loop is I am trying to avoid this summary[row.ItemTitle] += 1; and the negative performance implications of it. If there are any.

هل كانت مفيدة؟

المحلول

You can use LINQ GroupBy to get the result:

var summary = model.items.GroupBy(x => x.ItemTitle)
                         .ToDictionary(g => g.Key, g => g.Count());
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top