使用LINQ从查询其结果集一起返回的项目数 [英] Using Linq to return the count of items from a query along with its resultset

查看:472
本文介绍了使用LINQ从查询其结果集一起返回的项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#MVC4使用LINQ。

I am using C# MVC4 with Linq.

我已经使用依赖注入我的项目,这导致了我一个单独的存储库项目一起有一个单独的模型的项目(一个用于测试等)。所有这没有问题。

I have used dependency injection for my project which resulted in me having a separate Model's project along with a separate Repository project (and one for testing ect). All this no problem.

我把我的查询出控制器(老款)和到库中(新DI风格),并注入他们。它工作正常。

I moved my queries out of the controllers (old style) and into the repository (new DI style), and injected them. It works fine.

我有一个标准的LINQ查询(挑选任何例子,他们有足够的基础),它返回一组从数据库正常项目。这里没有任何问题。

I have a standard linq query (pick any example, they are basic enough), which returns a set of items from the database as normal. No problems here either.

我的问题是,我想实现分页,我教这将是足够简单到。下面是我的步骤:

My problem is, that I want to implement paging, and I taught it would be simple enough to. Here is my steps:

取(注入控制器)将其存储在一个变种。它看起来是这样的:

Take in the results of the linq query from the repository (injected into the controller) store it in a var. It looks something like:

var results = _someInjectedCode.GetListById(SomeId);

之前,我能够做一些简单的像:

Before, I was able to do something simple like:

results.Count()
results.Skip(SomeNum).Take(SomeOtherNum)

但现在,我想分页,我需要做我跳过拿这样的事情:

But now that I want paging, I need to do my Skip Take something like this:

var results = from xyz in _someInjectedCode.GetListById(SomeId).SomeId).Skip(SomeNum).Take(SomeOtherNum)
select new[] {a,id, a.fName, a.lName .....}

这样做的问题是,我不再有机会获得物品的总数之前,名单被缩短为pre跳过......就拿状态,除非我做两个查询,这意味着击中两次DB。

The problem with this is that I no longer have access to the total count of items before the list was shortened to the Pre Skip...Take state unless I do two queries which means hitting the DB twice.

什么是解决这一问题的最佳途径。

What is the best way to resolve this issue.

推荐答案

我只是做这样的:

var result = (from n in mycollection 
              where n.someprop == "some value" 
              select n).ToList();
var count = result.Count;

有可能是其他的方法,但是这是我所知道的最简单的。

There are probably other ways, but this is the simplest that I know of.

这篇关于使用LINQ从查询其结果集一起返回的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆