开发者

Chained selects with where at the end

开发者 https://www.devze.com 2023-04-02 05:31 出处:网络
Given following structure: a person has functions. Each function has roles. Each roles has features. Now I would like to figure out with linq if a given person has a certain feature, but I am doing so

Given following structure: a person has functions. Each function has roles. Each roles has features. Now I would like to figure out with linq if a given person has a certain feature, but I am doing something wrong with this query. As a result I always get the count of the functions (but I'd like to get the count of the features):

var count = person.Functions
                  .Select(fu => fu.Roles
         开发者_StackOverflow                         .Select(r => r.Features
                                                .Where(f => f.FeatureId == 99999)))
                  .Count();

What am I doing wrong here? According to this query I expect either 0 (hasn't got the feature) or 1.


var query = from function in person.Functions
            from role in function.Roles
            from feature in role.Features
            where feature.FeatureId == 99999
            select feature;

var count = query.Count();

or

var count = person.Functions
                  .SelectMany(function => function.Roles)
                  .SelectMany(role => role.Features)
                  .Count(feature => feature.FeatureId == 99999);

If you don't need the exact count but just want to know if the person has the feature or not, use Any instead of Count.


var count = person.Functions
             .SelectMany(p => p.Roles)
             .SelectMany(r => r.Features)
             .Where(f => f.FeatureId == 99999)
             .Count(); 

I'm not really sure, but I think you want the total number of Features with teh given Id. You would want to use SelectMany.

0

精彩评论

暂无评论...
验证码 换一张
取 消