如何存储linq查询?



我已经调查过了,但是没有发现任何关于这种情况的信息。

我有两个linq查询:
//checking all columns if there is
mockDataList = mockDataList.Where(w =>
w.Email.ToLower().Contains(search)          ||
w.Gender.ToLower().Contains(search)         ||
w.Name.ToLower().Contains(search)           ||
w.Surname.ToLower().Contains(search)        ||
w.Id.ToString().ToLower().Contains(search)
).Skip(start).Take(length).ToList();
//getting count info
var filteredTotal = mockDataList.Where(w =>
w.Email.ToLower().Contains(search) ||
w.Gender.ToLower().Contains(search) ||
w.Name.ToLower().Contains(search) ||
w.Surname.ToLower().Contains(search) ||
w.Id.ToString().ToLower().Contains(search)
).Count();

我想在取10个之前数一下。因此,我必须编写两个查询。我不想让它复制。如何在不执行查询的情况下进行存储?

*对不起我的语法错误

LINQ查询被执行,当你通过foreach或当你调用方法像FirstOrDefault(),ToList(),ToArray(),…所以下面的代码没有问题:

var query = mockDataList.Where(w =>
w.Email.ToLower().Contains(search)          ||
w.Gender.ToLower().Contains(search)         ||
w.Name.ToLower().Contains(search)           ||
w.Surname.ToLower().Contains(search)        ||
w.Id.ToString().ToLower().Contains(search)
); // nothing is done here, no filtering
mockDataList  = query.Skip(start).Take(length).ToList(); // here, the filtering is done
var filteredTotal = query.Count(); // here, the filtering is done again

将LINQ查询存储在本地变量中:

var query = mockDataList.Where(w =>
w.Email.ToLower().Contains(search) ||
w.Gender.ToLower().Contains(search) ||
w.Name.ToLower().Contains(search) ||
w.Surname.ToLower().Contains(search) ||
w.Id.ToString().ToLower().Contains(search));
var filteredTotal = query.Count();
mockDataList = query.Skip(start).Take(length).ToList();

我认为更好的做法是按照@SomeBody的建议存储IEnumerable。

IEnumerable<MyClass> query = mockDataList.Where(w => .....);
List<MyClass> PaginatedFilteredItems = query.Skip(start).Take(length).ToList();
int FilteredItemsTotal = query.Count();
// Or
int PaginatedFilteredItemsTotal = PaginatedFilteredItems.Count;

另一种方法是使用Func或Expression来存储查询:

public class MyClass{
public int Id;
public string Email;
public string Gender;
public string Name;
public string Surname;  
}
Func<MyClass, bool> MyClassFunc = w =>
w.Email.ToLower().Contains(search)          ||
w.Gender.ToLower().Contains(search)         ||
w.Name.ToLower().Contains(search)           ||
w.Surname.ToLower().Contains(search)        ||
w.Id.ToString().ToLower().Contains(search);

那么你可以这样使用:

mockDataList = mockDataList.Where(MyClassFunc).Skip(start).Take(length).ToList();

相关内容

  • 没有找到相关文章

最新更新