1

I have array:

OrderProduct[] OrderProductsOrder = new OrderProduct[] { 
new OrderProduct { OrderID = 1, ProductID = 2, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 1, ProductID = 3, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 2 }, 
new OrderProduct { OrderID = 1, ProductID = 2, OrderCustomerID = 3 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 3 }};

How to split this array to three arrays, order by CustomerID, using linq. Result should be this three arrays:

OrderProduct[] Customer1Order = new OrderProduct[] { 
new OrderProduct { OrderID = 1, ProductID = 2, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 1 }, 
new OrderProduct { OrderID = 1, ProductID = 3, OrderCustomerID = 1 }};

OrderProduct[] Customer2Order = new OrderProduct[] 
{new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 2 }};

OrderProduct[] Customer3Order = new OrderProduct[] {  
new OrderProduct { OrderID = 1, ProductID = 2, OrderCustomerID = 3 }, 
new OrderProduct { OrderID = 2, ProductID = 1, OrderCustomerID = 3 }};
1
  • do you consider using GroupBy(x => x.OrderCustomerID) ? Commented Sep 21, 2016 at 8:44

2 Answers 2

1

Edited, removed the GroupBy() suggestion as it was redundant (courtesy of Innat3)

No reason to use GroupBy() at all, just use Where.

OrderProduct[] Customer1Order = OrderProductsOrder.Where(o => o.OrderCustomerID == 1).ToArray();

OrderProduct[] Customer2Order = OrderProductsOrder.Where(o => o.OrderCustomerID == 2).ToArray();

OrderProduct[] Customer3Order = OrderProductsOrder.Where(o => o.OrderCustomerID == 3).ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

Your code is invalid, there is no need for a GroupBy if you are going to filter them with a .Where condition, use: OrderProduct[] Customer1Order = OrderProductsOrder.Where(o => o.OrderCustomerID == 1).ToArray();
In my zombie mindset, I completely missed that. You're right.
Might want to Replace o.Key with o.OrderCustomerID though, to avoid confusion
1

Start by grouping the entries by OrderCustomerID, and constructing an array from each group. After that, add groups to a dictionary:

var byCustId = OrderProductsOrder
    .GroupBy(p => p.OrderCustomerID)
    .ToDictionary(g => g.Key, g => g.ToArray());

Now you can grab individual arrays with TryGetValue or operator []:

OrderProduct[] customer2Order;
if (byCustId.TryGetValue(2, out customer2Order) {
    ... // Use customer2Order array
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.