1
class orders
{
    public string orderNumber { get; set; }
    public string id { get; set; }
    public List<string> idList { get; set; }
}

I have a list of orders that can be anywhere from 1 to 100. I need to assign each member of the list all of the "id"s of the other members of the list where the "orderNumber" is the same. I want to assign this to the "idList" list of strings. Within the list of orders, there might be multiple sets of orders that have the same "orderNumber".

I've tried to logically think this out but cannot come up with a solution that works.

I tried the following:

List<string> temp = new List<string>();
            for (int x = 0; x < orders.Count; x++)
            {

                if (string.Equals(orders[x].orderNumber, orders[x + 1].orderNumber))
                {
                    temp.Add(orders[x].id);
                    temp.Add(orders[x + 1].id);
                    i++;
                }
                else
                {
                    for(int o = 0; o < i; o++)
                    {
                        orders[o].idList= new List<string>();
                        orders[o].idList= temp;
                    }

                    i = 0;
                    temp.Clear();
                }
            }
2
  • "cannot come up with a solution that works." -- show us solutions that didnt work then. We aren't a code writing service Commented Oct 31, 2018 at 19:46
  • I tried using a for loop and match on orders[x].orderNumber == orders[x + 1].orderNumber and then add both "id"s to a list of strings and increment a count. Once the loop finds the next orderNumber where it doesn't match, I assign the list of strings to the "idList" of each order using another for loop that goes up to the count. This would work for 1 set of orders that have the same orderNumber but not multiples. Commented Oct 31, 2018 at 19:56

1 Answer 1

2

You may GroupBy the orderNumber, and join ids of those within the same group:

var result = orders.GroupBy(x => x.orderNumber).Select(g => new orders{
           orderNumber  = g.Key,
           idList = g.Select(x => x.Id).ToList()
          }

However as you don't really need a list of orders so its better to either select an anonymous type:

.Select(g => new {
               orderNumber  = g.Key,
               idList = g.Select(x => x.Id).ToList()
              }

Or just create a new type of class like:

class FinalOrder { public string orderNumber; public List idList ; }

and then:

.Select(g => new FinalOrder{
               orderNumber  = g.Key,
               idList = g.Select(x => x.Id).ToList()
     }
Sign up to request clarification or add additional context in comments.

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.