gpt4 book ai didi

c# - 如何编写可重用的 linq 查询

转载 作者:太空狗 更新时间:2023-10-30 00:52:08 25 4
gpt4 key购买 nike

在这里,我需要在两个地方(如 if 和 else 条件)进行微小更改以重用 linq 查询。如何编写可重用的 linq 查询

if(some condition){
comms = (from s in config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>()
from c in s.Communications.Cast<CommunicationConfiguration>()
where s.CurrentBrand == true
select c).ToList().FirstOrDefault();
}
else{
comms = (from s in config.Subscriptions.Cast<CommunicationGroupConfiguration>()
from c in s.Communications.Cast<CommunicationConfiguration>()
where s.CurrentBrand == true
select c).ToList().FirstOrDefault();
}

这里

config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>() 

仅这部分在这两个查询中发生了变化。如何有效地编写此查询。任何建议。

最佳答案

有一个正确类型的占位符:

IQueryable<CommunicationGroupConfiguration> temp = null;

if(some condition)
{
temp = config.PromoRegistration.Communications.Cast<CommunicationGroupConfiguration>();
}
else
{
temp = config.Subscriptions.Cast<CommunicationGroupConfiguration>();
}

comms =
(from s in temp
from c in s.Communications.Cast<CommunicationConfiguration>()
where s.CurrentBrand == true
select c).ToList().FirstOrDefault();

或者您可以使用三元运算符(我认为这更简洁):

comms = 
(from s in (<some condition> ? config.PromoRegistration.Communications : config.Subscriptions).Cast<CommunicationGroupConfiguration>()
from c in s.Communications.Cast<CommunicationConfiguration>()
where s.CurrentBrand == true
select c).ToList().FirstOrDefault();

关于c# - 如何编写可重用的 linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23343014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com