-3

I have 2 lists from database for US and CA.

List<Order> caList = DB.GetOrderData(Countries.CA);
List<Order> usList = DB.GetOrdersData(Countries.US);

I want to iterate both lists into 1 list using array element "US" and "CA" with foreach loop.

string[] countries = {'US','CA'};
foreach(){
}

I was able to combine 2 lists into 1 list using uslist.AddRange(calist) and it works.

co-worker told me this is another way to do it using foreach. I am new to IT and C#, I don't know where to start and couldn't figure it out the solution so asking fellow expert programmers for assistance to expand my c# knowledge. Thank you.

Joseph K.
  • 3
  • 2
  • `.Concat`...... – Daniel A. White Mar 12 '21 at 18:44
  • 2
    Fellow experts have answered this numerous times: [How do you concatenate Lists in C#?](https://stackoverflow.com/questions/1042219/how-do-you-concatenate-lists-in-c) – Ňɏssa Pøngjǣrdenlarp Mar 12 '21 at 18:47
  • @ Ňɏssa: Probably didn't read my post all the way. "I was able to combine 2 lists into 1 list using uslist.AddRange(calist)" and it works. I'm just trying to learn other ways because there is more then one solution to this problem. – Joseph K. Mar 12 '21 at 19:00

1 Answers1

-1

Use Enum.Parse to convert the string to an enum. Use SelectMany to get the lists into a single enumerable stream, and ToList to create the list.

string[] countries = {'US','CA'};
var combinedList = countries.SelectMany
    ( 
        x => DB.GetOrderData(Enum.Parse<Countries>(x))
    )
    .ToList();

If you'd rather do it with foreach here's how:

string[] countries = {'US','CA'};
var combinedList = new List<Order>();
foreach (var country in countries)
{
    var countryCode = Enum.Parse<Countries>(country);
    combinedList.AddRange(DB.GetOrderData(countryCode));
}

Or

string[] countries = {'US','CA'};
var combinedList = new List<Order>();
foreach (var country in countries)
{
    var countryCode = Enum.Parse<Countries>(country);
    var orders = DB.GetOrderData(countryCode);
    foreach (var order in orders)
    {
        combinedList.Add(order);
    }
}
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Thank you for the answer, John. This is all new to me and it will definitely help me get started. Is there anyway to use `foreach` on this? – Joseph K. Mar 12 '21 at 22:37
  • @JosephK.I've added additional examples to demonstrate the use of `foreach`. – John Wu Mar 12 '21 at 23:23