简体   繁体   中英

sort list by custom filter of string.contains

Need a bit of help here with some Linq queries.

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. 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?

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.

Any advice/pointers/help appreciated and apologies if this is a massive n00b question.. but we all need to learn somehow!

Thanks.

As Jens Kloster suggested, you should look at Dynamic Linq for this problem.

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.

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; be sure to check out the html page that comes with the download as it has better documentation than Scott Gu's post. Best of luck and feel free to ask again if I misunderstood something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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