按搜索条件C#LINQ排序

Ruu*_*uud 0 c# linq sorting

我有一个LINQ查询,它在多个字段中搜索字符串(使用正则表达式).我想根据找到文本的字段对结果进行排序.

目前我有这个:

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;
Run Code Online (Sandbox Code Playgroud)

我希望在Key中找到匹配项,然后在Other中找到匹配项,然后在Username中找到匹配项.如果可能,匹配Key和Other的匹配应该在匹配Key之前匹配.

我现在的代码基于Key排序,所以如果在Other上找到匹配但是Key以A开头,它将在Key上找到匹配之前排序,其中Key以Z开头.

提前谢谢,我认为这不是一个难题,但我不知道如何做到这一点,因为我是LINQ的新手.

dah*_*byk 7

使用let关键字捕获中间值,您可以在排序匹配的值之前轻松地根据是否匹配进行排序:

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;
Run Code Online (Sandbox Code Playgroud)