如何使用基于通用列表值的linq通过结果更改顺序。 [英] How to change the order by a result using linq based on the generic list values.

查看:106
本文介绍了如何使用基于通用列表值的linq通过结果更改顺序。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据整数类型泛型列表更改linq查询结果的顺序。

ex:



Linq我正在使用



var result = contect.tablename.where(somecondition).Tolist();

此结果包含一个代码id这是一个整数值。



我有另一个清单



List< int> sororder =新列表< int>();

sortorder.add(7);

sortOrder.add(9);





现在我需要根据上面的整数列表对结果进行排序。



任何帮助?

I need to change the order of a result of the linq query based on the integer type generic list.
ex :

Linq i am using

var result= contect.tablename.where(somecondition).Tolist();
This result contains one code id which is an integer value.

I have another list

List<int> sororder=new list<int>();
sortorder.add(7);
sortOrder.add(9);


Now i need to sort result based on the above integer list.

Any help?

推荐答案

简单地使用



var result = contect.tablename.where(somecondition).orderby(i => i ).Tolist();
Use simply

var result = contect.tablename.where(somecondition).orderby(i=>i).Tolist();


我的观点是,这是一个使用Linq的情况......虽然可能......可能是过度杀戮因为:你真的是什么做的非常任意。如果我理解你的目标,那就是将查询结果中的条目与另一个列表中的条目匹配到查询结果的前面。



对于你的情况查询结果包含重复值,您可以使用以下内容:
My opinion is that this is a case where using Linq ... while perhaps possible ... is probably "over-kill" because: what you are really doing is quite arbitrary. If I understand your goal, it is to move entries in a query result that match entries in another list to the front of the query result.

For the case that your query result doesn't contain duplicate values, you can use something like this:
private List<int> queryList = new List<int> {11, 42, 65, 33, 3, 5, 65, 5, 8};
        
private List<int>sortByList = new List<int> {65, 123, 42, 11};

int sortByInt;
int matchAt;

// somewhere in a method ...

// traverse the sortByList from back to front
// based on the assumption the desired result
// is a sort based on magnitude
for (int i = sortByList.Count - 1; i >= 0; i--)
{
    sortByInt = sortByList[i];

    if (queryList.Contains(sortByInt))
    {
        matchAt = queryList.IndexOf(sortByInt);
        queryList.RemoveAt(matchAt);
        queryList.Insert(0, sortByInt);
    }
}

这将处理在排序依据列表中没有出现在查询列表中的条目。

That would handle the case of having entries in the sort-by list that do not occur in the query list.


通过将整数列表与Linq结果集(带有关键元素)进行比较,将数据添加到新列表中,并使用此新列表进行进一步处理。这解决了我的问题。
By comparing the Integer list with Linq result set (with key element) added the data to the new list and used this new list for further process. This resolved my problem.


这篇关于如何使用基于通用列表值的linq通过结果更改顺序。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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