none
Please help me get the count to duplicated items using linq RRS feed

  • Question

  • var listSample = new List<string> {"apple", "banana", "apple", "cherry", "apple", "banana"};

    var q = from o in listSample 
            group o by o        
            select new {Value = g.Key, Count = count};

    Sunday, July 7, 2019 4:53 PM

Answers

  • var listSample = new List<string> {"apple", "banana", "apple", "cherry", "apple", "banana"};
    var qry = from o in listSample
            group o by o into grp
            let count = grp.Count()
            orderby count descending
            select new {Value = grp.Key, Count = count};
    foreach (var i in qry)
    {
        Console.WriteLine("Value: " + i.Value + " Count: " + i.Count);
    }

    or

    var qry = listSample.GroupBy(x => x)
                .Select(grp => new {Value = grp.Key, Count = grp.Count()})
                .OrderByDescending(x=>x.Count);

    foreach (var i in qry)
    {
        Console.WriteLine("Value: " + i.Value + " Count: " + i.Count);
    }
    • Marked as answer by AlexaKG Sunday, July 7, 2019 5:02 PM
    Sunday, July 7, 2019 4:57 PM