【问题标题】:LINQ concat predicate OR [duplicate]LINQ 连接谓词 OR [重复]
【发布时间】:2018-12-28 16:27:24
【问题描述】:

您好,我正在尝试连接 linq 表达式 例如:我有一个List<string[]>,我需要在其中循环阅读 我需要创建这样的查询

from table where (name ='someone' && id='123') || (name ='another one' && id='223') || ( name='noone' && id='456')

以下代码是我正在处理的代码

foreach (var item in data)
{
    var name= item[4];
    var cnpj = item[1];
    Expression<Func<IncidentIntegration, bool>> predicated = (x => (x.EmployeesBase.name== name && x.Branch.id== id));
    query = query.Union(query.Where(predicated));
 }

但它正在创建这样的查询

from table where (name ='someone' || name ='another one' || name='noone') && ( id='223' || id='123' || id='456')

有什么办法可以连接这个吗?

【问题讨论】:

  • 你的data数组的结构或者样本数据可以吗?

标签: c# linq lambda predicate


【解决方案1】:

您可以使用以下方法。它简单易用。头不需要处理动态表达式。

var result = list.Where(x => arr.Any(t => <your_condition>))

【讨论】:

  • 您确实意识到,您实际上根本没有使用xarr
  • 我试过这种方式,这是创建一个“和”而不是“或”,例如 (name='a' && id='1') AND (name ='b' && id='2 ')
  • 抱歉请检查我的编辑
【解决方案2】:

我想它可以帮助你

如果我们将 CompleteInfos 视为您的表格,那么:

public class CompleteInfos
{
    public int Id { get; set; }
    public string Name { get; set; }

    public string prop1 { get; set; }
    public string prop2 { get; set; }
}
public class Info{
    public int Id { get; set; }
    public string Name { get; set; }
}

List<CompleteInfos> Table = new List<CompleteInfos>(); 
// List contains your namse and ids
List<Info> infos = new List<Info>(){
        new Info(){Id = 123 , Name = "someone"},
        new Info(){Id = 223 , Name = "another"},
        new Info(){Id = 456 , Name = "noone"}
} 
foreach(var info in infos)
{
    List<CompleteInfos> selectedInfo = Table.Where(x => x.Id == info.Id || x.Name == info.Name).ToList();

    //selectedInfo  is the list in which you can find all item that have your desired id and name
}

【讨论】:

  • 嗯,我不使用 toList 的原因之一是因为我不想为每一行访问数据库,我可能有超过一千个,所以我只想制作一个查询,我担心这可能会加重连接
  • @MarcosBrinnerpikatoons 此过程不应每次都请求数据库。例如,您在数据库上运行 SELECT 查询,然后所有数据都将在 RAM 中
猜你喜欢
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-24
  • 2022-01-01
  • 2018-05-11
  • 2014-03-06
  • 1970-01-01
相关资源
最近更新 更多