如何使用linq获取前3个记录 [英] How to fetch top 3 records using linq

查看:56
本文介绍了如何使用linq获取前3个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var test = objIrPortalDB.spGetVersionData(Guid.Parse(ddlComponent.SelectedItem.Value));



变量test包含值

1.1.2

1.2.3

1.2.4

1.2.5等等



我想使用linq查询获取前3个值

我该怎么办...

var test= objIrPortalDB.spGetVersionData(Guid.Parse(ddlComponent.SelectedItem.Value));

variable "test" contains value of
1.1.2
1.2.3
1.2.4
1.2.5 and so on

I want o fetch top 3 value using linq query
how can i do that ...

推荐答案

在途中是订购商品并使用Take方法取结果中的前三项。请考虑以下代码

On way is to order the items and use Take method to take the first three items in the result. Consider the following code
System.Collections.Generic.List<string> testList = new System.Collections.Generic.List<string>();

testList.Add("1.2.5");
testList.Add("1.1.2");
testList.Add("1.2.4");
testList.Add("1.2.3");

var top3 = (from item in testList
            orderby item ascending
            select item).Take(3);

foreach (string item in top3) { }



但是,上面的代码应该记住以下几点:

- 如果列表如果总是需要3个元素,则结果可能少于3个项目

- 排序是基于字符串比较完成的,因此结果可能是意外的(取决于数据)


However, few things should be kept in mind with the code above:
- if the list has less than 3 items the result may be undesired if 3 elements are always expected
- the sorting is done based on string comparison so the result may be unexpected (depending on the data)


这篇关于如何使用linq获取前3个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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