LINQ - how can I get the value of most repeated duplicate value in the list?

Asked By chandu sekhar on 22-Aug-12 01:27 AM
Hi,

     I have list of strings (collection of emails). In that some are repeated. But how can i get the most repeated duplicate        value from the list.

Here is my LINQ code:

                    var q = from x in matchEmails group x by x into g let count = g.Count() orderby count descending select                                                                                 new { Value = g.Key, Count = count };
                foreach (var x in q)
                {
                    MessageBox.Show("Value: " + x.Value + " Count: " + x.Count);
                }

  But I want most repeated one among some duplicates.

 Thanks in-advance,
chandu.
Rolf Jaeger replied to chandu sekhar on 25-Aug-12 10:06 PM
Hi Chandu:

the code example listed below may not be the most elegant solution for your problem, but you might want to give its logic a try.

Hope this helped,
Rolf

private void FindMostFrequentlyRepeatedElement()
{
  List<string> l = new List<string>();
  l.Add("Item 1");
  l.Add("Item 1");
  l.Add("Item 2");
  l.Add("Item 3");
  l.Add("Item 4");
  l.Add("Item 4");
  l.Add("Item 4");
  var qDistinct = (from x in l select x).Distinct();
  int iMaxRepeat = 0;
  string sMax = String.Empty; //This string will contain the string most frequently repeated in the List
  foreach (string s in qDistinct)
  {
    var count = (from x in l where x == s select x).Count();
    if (count > iMaxRepeat)
    {
      iMaxRepeat = count;
      sMax = s;
    }
  }
}
chandu sekhar replied to Rolf Jaeger on 07-Sep-12 12:06 PM
Hi Rolf Jaeger,

  Thanks for your code. It helps me more.....


 chandu.