Posts Tagged LINQ

Count number of occurrences of distinct values using LINQ

C# code snippet below finds distinct (case-insensitive) strings in a collection and counts number of occurrences of each unique (case-insensitive again) one.

static void Main(string[] args)
        {

            string[] sa = { "ala", "ma", "ala", "ma", "ma", "abc" };

            var res = from uniqueString
                in sa.Distinct(StringComparer.CurrentCultureIgnoreCase).ToList()
                      select new { str = uniqueString, occur = sa.Count(s => s.ToLower().Equals(uniqueString.ToLower())) };


            foreach(var el in res){
                Console.Write(el.GetType().GetProperty("str").GetValue(el, null) +  "\t");
                Console.WriteLine(el.GetType().GetProperty("occur").GetValue(el, null));
            }

            Console.ReadLine();
        }

,

1 Comment