Home > Mobile >  What is the best way to find the most numerous duplicates present in a dictionary using LINQ?
What is the best way to find the most numerous duplicates present in a dictionary using LINQ?

Time:07-02

I have a dictionary that looks approximately like this:

            { 1, Value1 }
            { 2, Value1 }
            { 3, Value1 }
            { 4, Value1 }
            { 5, Value2 }
            { 6, Value2 }
            { 7, Value2 }
            { 8, Value3 }
            { 9, Value3 }
            { 10, Value3 }
            { 11, Value3 }
            { 12, Value3 }
            { 13, Value3 }

I am trying to find a way, using LINQ or otherwise, to isolate the most numerous duplicate. e.g., in this case it is going to be Value3 - and I am trying to obtain the number of times it has been duplicated.

My progress so far consists of the following implementation, so I was wondering if there is any better way:

            var SortedDict = OriginalDict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

            //Deduce the most common duplicate
            var List1 = SortedDict.Values.ToList().FindAll(x => x == "Value1");
            var List2 = SortedDict.Values.ToList().FindAll(x => x == "Value2");
            var List3 = SortedDict.Values.ToList().FindAll(x => x == "Value3");

            int MostCommon = new List<int>() { List1.Count, List2.Count, List3.Count }.Max();

In this case, my expected result would be 6 (Value3). Value2 would be 3 and Value1 would be 4.

Another problem I see is that if there is the same number of duplicates - in which case it would be best

CodePudding user response:

Try following :

            Dictionary<int, string> dict = new Dictionary<int, string>()
            {
                { 1, "Value1" },
                { 2, "Value1" },
                { 3, "Value1" },
                { 4, "Value1" },
                { 5, "Value2" },
                { 6, "Value2" },
                { 7, "Value2" },
                { 8, "Value3" },
                { 9, "Value3" },
                { 10, "Value3" },
                { 11, "Value3" },
                { 12, "Value3" },
                { 13, "Value3" }
            };
            var results = dict
                .GroupBy(x => x.Value)
                .Select(x => new { value = x.Key, count = x.Count() })
                .OrderByDescending(x => x.count)
                .FirstOrDefault();
  • Related