locked
LINQ GroupBy and MIn RRS feed

  • Question

  • Hi all,

    I have a simple class Item with 2 properties (string Category, int Price). A List<Item> is populated. I need to use LINQ to find the minimum price for each category, so I'm trying to do something like this:

                    var query = from i in items
                            group i by i.Category into p
                            select new { i.Category, Price = p.Min(x => x.Price) };

    But I get an error on i.Category: The name 't' does not exist in the current context

    What am I doing wrong?

    Thanks,

    Ivan


    Marketplace: [url=http://tinyurl.com/75gc58b]Itza[/url] - Review: [url=http://tinyurl.com/ctdz422]Itza Update[/url]

    Friday, October 26, 2012 9:20 AM

Answers

  • you create a new group P with a Key that has the value you group on so try this :

    var query = from i in items
                            group i by i.Category into p
                            select new { Category = p.Key, Price = p.Min(x => x.Price) };

    a great free  tool for learning and playing around with linq is LinqPad

    Hope this helps



    • Edited by KeesDijk Friday, October 26, 2012 10:20 AM
    • Marked as answer by Cryo75 Friday, October 26, 2012 10:27 AM
    Friday, October 26, 2012 10:18 AM

All replies

  • you create a new group P with a Key that has the value you group on so try this :

    var query = from i in items
                            group i by i.Category into p
                            select new { Category = p.Key, Price = p.Min(x => x.Price) };

    a great free  tool for learning and playing around with linq is LinqPad

    Hope this helps



    • Edited by KeesDijk Friday, October 26, 2012 10:20 AM
    • Marked as answer by Cryo75 Friday, October 26, 2012 10:27 AM
    Friday, October 26, 2012 10:18 AM
  • Now I get this error:

    'System.Linq.IGrouping<string,Item>' does not contain a definition for 'Category' and no extension method 'Category' accepting a first argument of type 'System.Linq.IGrouping<string,Item>' could be found (are you missing a using directive or an assembly reference?)


    Marketplace: [url=http://tinyurl.com/75gc58b]Itza[/url] - Review: [url=http://tinyurl.com/ctdz422]Itza Update[/url]

    Friday, October 26, 2012 10:25 AM
  • Problem solved. I didn't notice that Key is a property of the group!!

    Marketplace: [url=http://tinyurl.com/75gc58b]Itza[/url] - Review: [url=http://tinyurl.com/ctdz422]Itza Update[/url]

    Friday, October 26, 2012 10:26 AM