连接每个语句的两个列表

时间:2019-11-02 03:23:29

标签: c#

enter image description here

if (Settings.Default.All)
{
      List = new ObservableCollection<LexisNexis>(UnitOfWork.Query.Lexis.LexisForApprove2().OrderBy(x => x.TxnID).Reverse());             
}
if (Settings.Default.MLhuillier)
{
     List = new ObservableCollection<LexisNexis>(UnitOfWork.Query.Lexis.LexisForApprove2().Where(x => x.ServiceMode == "MLhuillier").OrderBy(x => x.TxnID).Reverse());
}
if (Settings.Default.BPI)
{
    List = new ObservableCollection<LexisNexis>(UnitOfWork.Query.Lexis.LexisForApprove2().Where(x => x.ServiceMode == "BPI").OrderBy(x => x.TxnID).Reverse());
}

我想合并每个返回true的if语句中的每个列表。我的程序只返回最后一个列表。 TYIA

1 个答案:

答案 0 :(得分:1)

简化代码

以下内容应该做的事很少,只需重复很少,并且最多遍历LexisForApprove2

var orFilters = Settings.Default.All ? null : new List<string>();

if (!Settings.Default.All)
{
    if (Settings.Default.MLhuillier) orFilters.Add("MLhuillier");
    if (Settings.Default.BPI) orFilters.Add("BPI");
}

var l = orFilters == null
    ? UnitOfWork.Query.Lexis.LexisForApprove2() // Everything
    : orFilters.Any() 
        ? UnitOfWork.Query.Lexis.LexisForApprove2().Where(x => orFilters.Contains(x.ServiceMode))
        : new List<LexisNexis>(); // Not 'All' but no others allowed

List = new ObservableCollection<LexisNexis>(l.OrderByDescending(y => y.TxnID));

Distinct

仅作记录,在这种情况下不建议使用,可以使用List的AddRange或Linq的Union,后跟Distinct,如果LexisNexis对象有效善于与他人进行比较:)

相关问题