Search code examples
linqasp.net-core

Merge two or more lists in a list?


I have two queries. I want to assign the list values ​​returned from these two queries to a single list, send it to the view and meet it in the view. My goal is to learn to work with lists in C#.

var list1 = c.ETs.Where(p => p.prop != "yes").ToList();
var list2 = c.ETs.Where(p => p.prop == "yes").ToList();

Solution

  • You can merge two lists into one with this:

    var newList = List1
        .Concat(List2)
        .ToList();
    

    Though you could drop the ToList and work directly with the IEnumerable which means you don't need to create a new object.

    However, this doesn't even need to be two queries since the Where clauses of both are opposite so they include the entire table, you could do:

    var list = c.ETs.ToList();
    

    Or if you want to have two different clauses that aren't simply opposites:

    var list = ct.ETs
        .Where(p => p.prop == "yes" || p.prop == "no")
        .ToList()` for example