开发者

Removing redunancies between LINQ queries

开发者 https://www.devze.com 2023-02-25 06:42 出处:网络
I need to call identical LINQ queries multiple times that only have differing elements in the \"where\" clause. Instead of repeating the LINQ query over and over again, I\'d like to pass the elements

I need to call identical LINQ queries multiple times that only have differing elements in the "where" clause. Instead of repeating the LINQ query over and over again, I'd like to pass the elements into a single query instead, but I'm brain stuttering on how to do that.

Right now my base LINQ query looks like this:

return from a in _repository.GetApps()
                       join set in _repository.GetSettings() on a.id equals set.application_id
                       join type in _repository.GetSettingsTypes() on set.setting_type_id equals type.id
                       join ent in _repository.GetEntities() on a.entity_id equals ent.id
                       where ent.ROW_ID == app && set.application_id == id && (set.setting_type_id==81 || set.setting_type_id==82 || set.setting_type_id==83)
                       orderby set.application_id, type.ordinal
                       select new Settings { app_name = a.name, data_type = type.data_type, set开发者_开发技巧ting_name = type.name, setting_description = type.description, setting_value = set.setting_value, entity_name = ent.name, entity_num = ent.ROW_ID };

The "where" clause just lists setting types by IDs. The other calls will simply replace that "where" clause with more or fewer setting ids which then get returned to a view. How can I dynamically replace that "where" clause or the setting ids? Can I simply assign a string or array to the setting list following the second "&&" (this didn't seem to work)? Or would Lambdas help here (I also couldn't get that to work)? Thanks!


You can use an array combined with a Contains() query:

var settingTypeIds = new[] { 81, 82, 83 };

return from a in _repository.GetApps()
..
where ent.ROW_ID == app 
      && set.application_id == id 
      && settingTypeIds.Contains(set.setting_type_id) 


Do you have to use Query syntax? Can you use LINQ extension methods and pass different lambda expressions into the Where method?

0

精彩评论

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

关注公众号