Home > Software design >  How do I query multiple lists as well as select multiple items
How do I query multiple lists as well as select multiple items

Time:11-19

I am fairly new to LINQ and querying in general.

My goal here is to take values from each list, compare them and then add the values from both lists to the resulting IEnumerable. This is my current working code, with the desired result but I wondering if there was a way to shorten or simplify it

query1a performs the query and selects all of the even numbers query1b performs the same query except it selects all of the odd numbers query1 gets all of the values from a union of query1a and query1b in ascending order

IEnumerable<int> query1a =
    (from e in evens
    from o in odds
    where e > o * 2
    select e).Distinct();

IEnumerable<int> query1b =
    (from e in evens
    from o in odds
    where e > o * 2
    select o).Distinct();

IEnumerable<int> query1 = from n in query1a.Union(query1b) orderby n ascending select n;

foreach (int item in query1)
{
    Console.WriteLine(item);
}

CodePudding user response:

I think you have a select problem because the first two queries are almost identical except you select the even number in the first query and the odd number in the second one. Then you have the third query where you merge the results and get an IEnumerable of unique and ordered integers.

If that sounds right, then you can do it all in one query:

var q = (from od in odds
            from ev in evens
            where ev > od * 2
            from n in new[] { od, ev }
            orderby n ascending
            select n).Distinct();
  • Related