按搜索条件排序C#LINQ [英] Sort by search criteria C# LINQ
问题描述
我有一个LINQ查询,它在多个字段中搜索字符串(使用正则表达式).我想根据在哪个字段中找到文本来对结果进行排序.
I have a LINQ query which searches for a string (using a regex) in multiple fields. I want to sort the results based on in which field the text was found.
目前我有这个:
var results = from i in passwordData.Tables["PasswordValue"].AsEnumerable()
where r.IsMatch(i.Field<String>("Key").Replace(" ","")) ||
r.IsMatch(i.Field<String>("Username").Replace(" ","")) ||
r.IsMatch(i.Field<String>("Other").Replace(" ",""))
orderby i.Field<String>("Key"),
i.Field<String>("Other"),
i.Field<String>("Username")
select i;
我希望先在密钥"中找到匹配项,然后再在其他"中找到匹配项,然后再在用户名"中找到匹配项.如果可能,匹配键"和其他"的匹配项应排在仅匹配键"的匹配项之前.
I want matches found in Key first, then matches found in Other, and then matches found in Username. If possible, matches which match both Key and Other should go before matches that match only Key.
我当前拥有的代码首先基于Key进行排序,因此,如果在Other上找到匹配项,但Key以A开头,则它将在Key上找到的匹配项(其中Key以Z开头)之前进行排序.
The code I currently have sorts based on Key first, so if a match is found on Other but Key starts with an A, it will be sorted before a match found on Key where Key starts with a Z.
预先感谢,我认为这不是一个很难的问题,但是由于我是LINQ的新手,所以我只是想不通该怎么做.
Thanks in advance, it isn't a hard question I think but I just can't figure out how to do this as I'm new to LINQ.
推荐答案
使用let
关键字捕获中间值,在对匹配的值进行排序之前,您可以轻松地按是否存在匹配项进行排序:
Using the let
keyword to capture intermediate values, you can easily sort by whether there was a match before you sort the matched values:
var results = from i in passwordData.Tables["PasswordValue"].AsEnumerable()
let fields = new {
Key = i.Field<String>("Key"),
Username = i.Field<String>("Username"),
Other = i.Field<String>("Other") }
let matches = new {
Key = r.IsMatch(fields.Key.Replace(" ","")),
Username = r.IsMatch(fields.Username.Replace(" ","")),
Other = r.IsMatch(fields.Other.Replace(" ","")) }
where matches.Key || matches.Username || matches.Other
orderby matches.Key descending, fields.Key,
matches.Username descending, fields.Username,
matches.Other descending, fields.Other
select i;
这篇关于按搜索条件排序C#LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!