Puchacz
Puchacz

Reputation: 2105

linq join with groups

Hej, i've got a problem with linq expression. I Would like to perform join with groups of some set. This is basicly what I need:

var f = new IEnumerable<SomeClass> { ... };
var rows = new IEnumerable<SomeOtherClass> { ... };
var makedGroups = rows.GroupBy(row => row.SomeId);
var groupsJoined = (from row in makedGroups
    join allocQuant in f on row.Key.Value equals allocQuant.SomeId into gj
    select gr => new { Count = gr.Count(), Group = gj });

error is: Error 202 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.

How to write this expression properly?

Upvotes: 1

Views: 98

Answers (1)

krystan honour
krystan honour

Reputation: 6803

I have included some sample code which is doing what you are trying to do. Its adapted from some sample code to use two classes rather than a static array of strings.

The result will yield an IEnumerable With a ProductCategory Field, Products Field which contains groupings of products based on the category and the last column is the count in the grouping.

From what you asked this is what I thought you wanted.

class Product
{

    public Product(string cat, string name)
    {
        Category = cat;
        ProductName = name;
    }

    public string Category { get; set;}
    public string ProductName { get;set;}
}


class ProductClass
{
    public ProductClass (string type)
    {
        ProductType = type;
    }   

    public string ProductType { get;set;}
}

ProductClass[] productClasses = new ProductClass[]{  
    new ProductClass("Beverages"),   
    new ProductClass("Condiments"),   
    new ProductClass("Vegetables"),   
    new ProductClass("Dairy Products"),   
    new ProductClass("Seafood") };  

List<Product> products = new List<Product>();
products.Add(new Product("Seafood", "crab sticks"));
products.Add(new Product("Seafood", "lobster"));
products.Add(new Product("Vegetables", "cucumber"));
products.Add(new Product("Seafood", "oysters"));
products.Add(new Product("Condiments", "pepper"));
products.Add(new Product("Condiments", "salt"));

var query =
    from pc in productClasses
    join product in products on pc.ProductType equals product.Category into gj
    select new { ProductCategory= pc.ProductType, Products = gj, Count = gj.Count() };

Upvotes: 2

Related Questions