2

I have two Lists (call them foo and bar) and I want to minimise the number of LINQ queries (okay, I know they have a minimal overhead, but still, two queries takes twice the time and LINQ with iOS development can be problematic). The query will be exactly the same, but I want to add the results to the two lists.

My current code looks like this

List<foo> foos = new List<foos>();
List<bar> bars = new List<bars>();

var agg = (from fa in mainList
           from pa in fa.subList
           from cg in pa.subSubList
           let cr = pa.anotherSubList
           where cg.DatePerformed.Year == DateTime.Now.Year - 1 && cr.Count != 0
           select foos.Add(fa)
           select bars.Add(pa));

The compiler is complaining at the second select.

Is there a way to do what I want to do in LINQ or am I going to need to use two loops?

1 Answer 1

1

You can select both items and iterate over the results to add one item to the first list and the other to the other list. You can do that with a class that can hold both items, a Tuple or just an anonymous type like this:

var result = from fa in mainList
    from pa in fa.subList
    from cg in pa.subSubList
    let cr = pa.anotherSubList
    where cg.DatePerformed.Year == DateTime.Now.Year - 1 && cr.Count != 0
    select new {First=fa, Second=pa};
foreach (var pair in result)
{
    foos.Add(pair.fa);
    bars.Add(pair.pa);
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's great - pity there isn't really a way to add directly to the Lists from within the query. I wonder how much of a hit having the query and the foreach would be over having the two queries. I did consider using Union, but again, doesn't quite hit what I want to do.
1. You could convert the linq to a iterative foreach statements. 2. If you measure in big O notation, it's exactly the same.
Actually, if that's linq to objects it is exactly the same, because it's built on yields.

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.