简体   繁体   English

通过string.contains的自定义过滤器对列表进行排序

[英]sort list by custom filter of string.contains

Need a bit of help here with some Linq queries. 这里需要一些Linq查询的帮助。

I'm trying to put together a list in a custom order which I can do for two of the parameters that I am trying to sort by, but the third one seems much harder to do. 我正在尝试以自定义顺序整理一个列表,我可以对要尝试排序的两个参数执行此操作,但是第三个参数似乎更难处理。

What I have at the moment is: 我目前所拥有的是:

return this.currentDocuments.OrderByDescending(x => x.Created).ThenBy(x => x.Description).toList();

Now I need to add a third parameter which is set by the string in an XML field. 现在,我需要添加第三个参数,该参数由XML字段中的字符串设置。 I've got a field that is just a string of letters and need to use the last two letters of the string to define the order. 我有一个只是字母字符串的字段,需要使用字符串的最后两个字母来定义顺序。

Can anyone enlighten me as to how I would do this? 有人能启发我如何做到这一点吗? is this something that can be done with Linq or do I need to write a separate method to do this? 这是Linq可以完成的事情,还是我需要编写一个单独的方法来做到这一点?

Also, there are 9 different options available for what's output in the last two digits of the string so I need to find the easiest way to work with all the options. 另外,在字符串的后两位数字中有9种不同的输出选项,因此我需要找到使用所有选项的最简单方法。

Any advice/pointers/help appreciated and apologies if this is a massive n00b question.. but we all need to learn somehow! 任何建议/指针/帮助表示赞赏和歉意,如果这是一个很大的n00b问题。.但是我们都需要学习某种方式!

Thanks. 谢谢。

As Jens Kloster suggested, you should look at Dynamic Linq for this problem. 正如Jens Kloster所建议的那样,您应该针对此问题查看Dynamic Linq。

Check out this post for examples and the code. 查看这篇文章,获取示例和代码。 The one limitation is that you have to use IQueryable<T> instead of IEnumerable<T> but that might not be a problem. 一个限制是您必须使用IQueryable<T>而不是IEnumerable<T>但这可能不是问题。

Your code would then look something like this: 您的代码将如下所示:

var sortingCodeToSortField = new Dictionary<string,string>
    { {"ei", "EmployeeId"}, {"na", "Name"}, {"ag", "Age" } };

string sortCode = GetSortCodeFromXml(inputXml);
string fieldToSortOn = sortingCodeToSortField[sortCode];

var whatYouHaveSoFar = this.currentDocuments.OrderByDescending(x => x.Created).ThenBy(x => x.Description);

var whatYouWant = whatYouHaveSoFar.AsQueryable.OrderBy(fieldToSortOn);

return whatYouWant.ToList();

The Dynamic Linq library can be a little goofy; 动态Linq库可能有点愚蠢; be sure to check out the html page that comes with the download as it has better documentation than Scott Gu's post. 请务必查看下载随附的html页面,因为它比Scott Gu的帖子具有更好的文档。 Best of luck and feel free to ask again if I misunderstood something. 祝您好运,请随时询问我是否误解了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM