I want to search through a user database and order my results according to how precise the match is. Exact matches on a users name should appear in the result before single word matches, as an example.
我想通过用户数据库进行搜索,并根据匹配的精确程度排列结果。一个用户名的精确匹配应该出现在单个单词匹配之前的结果中。
This is what i have (the variable 'value' contains a search term and 'query' contains an initial queryable i want to modify)
这就是我所拥有的(变量“值”包含一个搜索项,“查询”包含一个初始的可查询的,我想要修改)
var values = value.Split(new [] {' ','\t', '\n', '\r'});
var q1 = query.Where(u => u.Id == valueAsInt || u.ExternalId == valueAsInt);
var q2 = query.Where(u => u.Name.Contains(value) || u.Username.Contains(value));
var q3 = query.Where(u => values.All(i => u.Name.Contains(i)) || values.All(i => u.Username.Contains(i)));
var q4 = query.Where(u => values.Any(i => u.Name.Contains(i)) || values.Any(i => u.Username.Contains(i)));
However, I now want to combine the results of q1 through q4 and have a new queryable which i can pass along. I also want to preserve the order of my queries, and frankly I have no idea how to go about doing this..
然而,我现在想把q1的结果和q4结合起来,并且有一个新的可查询的,我可以通过。我还想保留我的查询顺序,坦白地说,我不知道该怎么做。
2 个解决方案
#1
0
Answered by Silas Hansen in the comments
西拉斯·汉森在评论中回答。
#2
0
You should use ranking. e.g.
您应该使用排名。如。
var result = query.Select(u =>
{
if (u.Id == valueAsInt || u.ExternalId == valueAsInt)
return new {Rank = 1, Item = u};
if (u.Name.Contains(value) || u.UserName.Contains(value) )
return new {Rank = 2, Item = u};
//Add the other conditions in here
return new {Rank = 3, Item = u};
}).OrderBy(u => u.Rank).Select(u => u.Item);
#1
0
Answered by Silas Hansen in the comments
西拉斯·汉森在评论中回答。
#2
0
You should use ranking. e.g.
您应该使用排名。如。
var result = query.Select(u =>
{
if (u.Id == valueAsInt || u.ExternalId == valueAsInt)
return new {Rank = 1, Item = u};
if (u.Name.Contains(value) || u.UserName.Contains(value) )
return new {Rank = 2, Item = u};
//Add the other conditions in here
return new {Rank = 3, Item = u};
}).OrderBy(u => u.Rank).Select(u => u.Item);