gpt4 book ai didi

LINQ OrderBy : best search results at top of results list

转载 作者:行者123 更新时间:2023-12-01 22:57:34 25 4
gpt4 key购买 nike

考虑需要按名字和姓氏搜索客户列表。我们希望让搜索词中匹配最多的客户对结果列表进行排序。

FirstName      LastName----------     ---------Foo            LaurieBar            JacksonJackson        BroLaurie         FooJackson        Laurie
string[] searchTerms = new string[] {"Jackson", "Laurie"};

//want to find those customers with first, last or BOTH names in the searchTerms
var matchingCusts = Customers
.Where(m => searchTerms.Contains(m.FirstName)
|| searchTerms.Contains(m.LastName))
.ToList();

/* Want to sort for those results with BOTH FirstName and LastName
matching in the search terms. Those that match on both First and Last
should be at the top of the results, the rest who match on
one property should be below.
*/

return matchingCusts.OrderBy(m=>m);

期望排序:
Jackson        Laurie  (matches on both properties)
Foo Laurie
Bar Jackson
Jackson Bro
Laurie Foo

我如何使用 LINQ 和 OrderBy 实现此所需功能/ OrderByDescending ?

最佳答案

使用 Select与客户进行“匹配评估”,然后按以下顺序订购:

class Program
{
static void Main(string[] args)
{
var Customers = new Customer[]
{
new Customer { FirstName = "Foo", LastName = "Laurie" },
new Customer { FirstName = "Bar", LastName = "Jackson" },
new Customer { FirstName = "Jackson", LastName = "Bro" },
new Customer { FirstName = "Laurie", LastName = "Foo" },
new Customer { FirstName = "Jackson", LastName = "Laurie" },
};

string[] searchTerms = new string[] { "Jackson", "Laurie" };

//want to find those customers with first, last or BOTH names in the searchTerms
var matchingCusts = Customers
.Where(m => searchTerms.Contains(m.FirstName)
|| searchTerms.Contains(m.LastName))
.ToList();

var result = matchingCusts.Select(x => new
{
Customer = x,
MatchEvaluation = (searchTerms.Contains(x.FirstName) ? 1 : 0) + (searchTerms.Contains(x.LastName) ? 1 : 0),
})
.OrderByDescending(x => x.MatchEvaluation)
.Select(x => x.Customer);

foreach (var c in result)
{
Console.WriteLine(c.FirstName + " " + c.LastName);
}

Console.ReadKey();
}

public sealed class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}

关于LINQ OrderBy : best search results at top of results list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2868060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com