gpt4 book ai didi

c# - 动态 Linq 查询帮助?

转载 作者:太空宇宙 更新时间:2023-11-03 20:30:18 25 4
gpt4 key购买 nike

如何为以下简单搜索条件编写动态 Linq 查询?1) 学号2) 姓氏3) 姓和名

//if (!String.IsNullOrEmpty(StudentNumber))
var results = (from s in Students
where s.StudentNumber == 1001
select s
);

//else if (!String.IsNullOrEmpty(LastName) & (String.IsNullOrEmpty(FirstName))

var results = (from s in Students
where s.LastName == "Tucker"
select s
);

//else if (!String.IsNullOrEmpty(LastName) & (!String.IsNullOrEmpty(FirstName))
var results = (from s in Students
where s.LastName == "Tucker" && s.FirstName == "Ron"
select s
);

最佳答案

您需要申报您的 results任何单个查询之外的变量。这将允许您根据不同的标准附加不同的过滤器,并根据需要附加尽可能多的过滤器。一个例子:

var results = Students.AsEnumerable(); // use .AsQueryable() for EF or Linq-to-SQL

if (!string.IsNullorEmpty(StudentNumber))
{
results = results.Where(s => s.StudentNumber.Equals(StudentNumber));
}
else if (!string.IsNullOrEmpty(LastName))
{
results = results.Where(s => s.LastName.Equals(LastName));

if (!string.IsNullOrEmpty(FirstName))
{
results = results.Where(s => s.FirstName.Equals(FirstName));
// filter is in addition to predicate against LastName
}
}

// results can be used here

如果处理 Linq-to-Entities 或 -Sql,请使用 Students.AsQueryable(); 键入初始查询这样过滤就发生在数据库而不是应用程序内部。


Is there a way I can construct the WHERE clause first and use it in a Linq query without if...else

如果你想构建整个where在查询的第一步之前,它是相同的逻辑。您正在有条件地构建谓词,因此您将涉及某种 if/else。但是,要首先构建整个谓词,您可以针对 Func<Student, bool> 构建对于 Linq to Objects。

Func<Student, bool> predicate;
if (!string.IsNullOrEmpty(StudentNumber))
{
predicate = s => s.StudentNumber.Equals(StudentNumber);
}
else if (!string.IsNullOrEmpty(LastName))
{
predicate = s => s.LastName.Equals(LastName);

if (!string.IsNullOrEmpty(FirstName))
{
Func<Student, bool> p = predicate;
predicate = s => p(s) && s.FirstName.Equals(FirstName);
}
}
else
{
predicate = s => true;
}

var query = Students.Where(predicate);

您会注意到它是完全相同的 if/else 结构。你可以把它分解成一个复杂的条件表达式

Func<Student, bool> predicate;
predicate = s =>
!string.IsNullOrEmpty(StudentNumber)
? s.StudentNumber.Equals(StudentNumber)
: !string.IsNullOrEmpty(LastName)
? !string.IsNullOrEmpty(FirstName)
? s.LastName.Equals(LastName) && s.FirstName.Equals(FirstName)
: s.LastName.Equals(LastName)
: true;

var query = Students.Where(predicate);

但我发现这很难理解,尤其是与较长的 if/else 相比。这个谓词也比我们通过 if/else 构建的谓词更大,因为这个谓词包含了所有逻辑,而不仅仅是我们有条件添加的逻辑。

关于c# - 动态 Linq 查询帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7862703/

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