Vaccano
Vaccano

Reputation: 82291

Grouping with linq; But with conditions

I am having trouble wrapping my head on how to group a list of these classes.

public class Order
{
    public int OrderId { get; set; }
    public long OrderClassId { get; set; }
    public int OrderTypeId { get; set; }
    public int OrderSubTypeId { get; set; }
    public string OrderString { get; set; }
    //.. other Order stuff not relevant to question
}

The basic grouping I understand. It looks like this (assume orders is a List<Order>):

var orderGroups = orders.GroupBy(x=>x.OrderClassId);

// Code to assign a unique OrderString to each group goes here

However, orders that have the same OrderClassId and have an OrderTypeId of 123 and have the same OrderSubTypeId need to have different OrderString values.

That is a bit confusing, so here is an example:

var order1 = new Order
                    {
                        OrderId = 1,
                        OrderClassId = 8754,
                        OrderTypeId = 123,
                        OrderSubTypeId = 7156
                    };

var order2 = new Order
                    {
                        OrderId = 2,
                        OrderClassId = 8754,
                        OrderTypeId = 123,
                        OrderSubTypeId = 7156
                    };

var order3 = new Order
                    {
                        OrderId = 3,
                        OrderClassId = 8754,
                        OrderTypeId = 951,
                        OrderSubTypeId = 35144
                    };

With my grouping, all of these would get the same OrderString. But I need order2 to get a different OrderString.

Is that possible using linq? Or am I just going to have to iterate all the rows and manually separate the ones that match my criteria.

Upvotes: 1

Views: 144

Answers (4)

Gert Arnold
Gert Arnold

Reputation: 109080

I think this is what you could use (OrderId is unique, right?):

orders.GroupBy(o => 
  new {
    o.OrderClassId,
    OrderIdSel = o.OrderTypeId == 123 ? o.OrderId : -1
  } )

Upvotes: 2

Amy B
Amy B

Reputation: 110071

You can do conditions as you generate the keys.

var groups = orders.GroupBy(x => new
{
  x.OrderClassId,
  TypeChoice = (x.OrderTypeId == 123) // ? true : false
}

Upvotes: 2

Surjit Samra
Surjit Samra

Reputation: 4662

As Kirill says just use var orderGroups = orders.GroupBy(x => new { x.OrderClassId, x.OrderSubTypeId });

Upvotes: 1

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use anonymous type, e.g.:

var orderGroups = orders.GroupBy(x => new {Property1, Property2});

Upvotes: 2

Related Questions