1

I've got a LINQ query which looks like this:

var query = from produkt in Entity.ProduktCollection.produktCollection
            let p = produkt as Entity.Produkt

            from version in p.version
            let v = version as Entity.Version

            from customer in v.customerCollection
            let c = customer as Entity.Customer

            from fehler in v.fehlerCollection
            let f = fehler as Entity.Fehler

            where f.id == GetGuid();
            select p;

but what I really need is a way to make the f plus its property as well as the p variable, so I might change them to every other possible combination, for example:

where c.name == "frank"
select f;

or

where p.id == GetGuid2()
select c;

Is there any way to achieve this? As far as I know there is no way to insert a switch-case block inside the query between the from/let-part and the where/select-part.

1 Answer 1

6

You can create your query in multiple statements because LINQ queries execution is deferred. It applies nicely to different Where statements situation:

var querySource = from produkt in Entity.ProduktCollection.produktCollection
                  let p = produkt as Entity.Produkt
                  from version in p.version
                  let v = version as Entity.Version
                  from customer in v.customerCollection
                  let c = customer as Entity.Customer
                  from fehler in v.fehlerCollection
                  let f = fehler as Entity.Fehler
                  select new { p, v, c, f };

if(/* first condition */)
{
    querySource = querySource.Where(x => x.f.id == GetGuid());
}
else if(/* second condition */)
{
    querySource = querySource.Where(x => x.p.id = 34);
}

var query = querySource.Select(x => x.p);

You can make the Select part conditional as well, but because returned IEnumerable<T> will differ in T part, you won't be able to assign them all to the same variable.

Sign up to request clarification or add additional context in comments.

1 Comment

This is great, i hoped something like this might work! The only problem which is left: now i've got all different types inside my query. I tried to specify with "query = query.Where(x=>x.GetType() == T);" but this istn't working, is there a way to make this possible?

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.