Sven Heinz
Sven Heinz

Reputation: 51

Linq:How to write Any in query syntax?

IEnumerable<Gruppe> cand = (IEnumerable<Gruppe>)populations.Where(
                            x => !x.Attributes.Any(
                                 y => y.GetType() == typeof(Arbeit)
                              )
                          );

I wondered how I could write the above in query syntax but stumbled because of the Any method.

Upvotes: 0

Views: 1719

Answers (3)

B. Mahler
B. Mahler

Reputation: 1

I like Svik's answer.

Another way to put it is like this:

IEnumerable<Gruppe> cand = 
    from population in populations
    where ( from attribute in population.Attributes
        where attribute.GetType() == typeof(Arbeit)
        select true).Any() == false
    select population

Upvotes: 0

user11523568
user11523568

Reputation:

The Any could be refactored out, but you are still going to need a Count.

var cand = from population in populations
           let attributeCount = population.Attributes.Count
           let validAttributeCount = (
               from attribute in population.Attributes
               where attribute.GetType() != typeof(Arbeit)
               select attribute
           ).Count()
           where attributeCount == validAttributeCount
           select population;

Upvotes: 0

svick
svick

Reputation: 244777

There is no equivalent of Any in query syntax. So the best you can do is:

IEnumerable<Gruppe> cand =
   from population in populations
   where !population.Attributes.Any(y => y.GetType() == typeof(Arbeit))
   select population

(I'm assuming that the cast to IEnumerable<Gruppe> is not necessary. If that assumption is wrong, you will need to add it back.)

Upvotes: 1

Related Questions