0

I'd like to know how to Count the instances of the first element in a list, then the second etc. and output these values.

var SPFK_List = new List<string>() { "one", "one", "one", "two", "two", "three", "three", "three" }; Inputs.ones.Value = *(number of one's)* Inputs.twos.Value = *(number of two's)* 
1
  • Thanks for the responses! My final code included: Inputs.first.Value = List.Where(x => x.Equals(Distinct_List[2])).Count(); Where the distinct list is a list of added distinct values from the first list. Commented Feb 13, 2020 at 12:20

3 Answers 3

5

Try GroupBy (Linq), e.g.:

using System.Linq; ... var SPFK_List = new List<string>() { "one", "one", "one", "two", "two", "three", "three", "three" }; // {3, 2, 3} int[] counts = SPFK_List .GroupBy(item => item) .Select(group => group.Count()) .ToArray(); 

Or (add Where if you want to count only some items)

// {{"one", 3}, {"two", 2}, {"three", 3}} Dictionary<string, int> counts = SPFK_List //.Where(item => item == "one" || item == "two") .GroupBy(item => item) .ToDictionary(group => group.Key, group => group.Count()); Inputs.ones.Value = counts.TryGetValue("one", out int count) ? count : 0; 
Sign up to request clarification or add additional context in comments.

Comments

4

A possible solution:

Inputs.ones.Value = SPFK_List.Where(x => x.Equals("one")).Count(); 

2 Comments

You could replace Where with Count and remove the last Count to make if even simplier.
@MightyBadaboom: didn't think about it, feel free to edit if you have optimizations.
2

Simply use Count method from System.Linq with overload accepting a Func<TSource,bool> predicate

var SPFK_List = new List<string>() { "one", "one", "one", "two", "two", "three", "three", "three" }; Inputs.ones.Value = SPFK_List.Count(s => s.Equals("one", StringComparison.Ordinal)); Inputs.twos.Value = SPFK_List.Count(s => s.Equals("two", StringComparison.Ordinal)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.