我用更清晰的样本数据来重述问题,以帮助成员更好地理解我的问题。
我使用linq进行相当基本的查询,但不知道如何编写复杂的查询。我在列表中有这样的数据,
var list = new List<Users>()
{
new Users() { FirstName = "John", LastName= "Doe", MiddleName = "P.", Phone = "111-111-111", Email = "abc@xyz.com" },
new Users() { FirstName = "Alex", LastName= "Jones", MiddleName = "S", Phone = "333-333-222", Email = "xyz@abc.com" },
new Users() { FirstName = "John", LastName= "Doe", MiddleName = "p.", Phone = "111-111-111", Email = "abc@xyz.com" },
new Users() { FirstName = "John", LastName= "Doe", MiddleName = "", Phone = "111-222-111", Email = "abc@xyz.com" },
new Users() { FirstName = "John", LastName= "", MiddleName = "", Phone = "111-111-111", Email = "abc@xyz.com" },
new Users() { FirstName = "Alex", LastName= "James", MiddleName = "N", Phone = "111-111-111", Email = "cde@xyf.com" },
new Users() { FirstName = "Alex", LastName= "Jones", MiddleName = "S", Phone = "333-333-222", Email = "xyz@abc.com" },
new Users() { FirstName = "John", LastName= "Doe", MiddleName = "", Phone = "111-222-111", Email = "" },
};
这些只是用户的样本记录,有数千条这样的记录。我想对用户进行排序/分组,以便对于单个用户(FirstName,LastName),最顶层的记录将是FirstName,LastName,MiddleName,Phone和Email匹配的记录。在这些记录需要来之后,FirstName,LastName,MiddleName和Phone匹配。因此,具有最匹配列的行将位于顶部,而具有最少匹配列的行将位于底部。单个用户的行不应与其他用户重叠,因此类似的用户记录将在一起。
我尝试过:
我使用了以下Linq查询来实现所需的结果,
obj = obj.OrderBy(x => (chkFirstName.Checked) ? x.FIRSTNAME : "")
.ThenBy(x => (chkLastName.Checked) ? x.LASTNAME : "")
.ThenBy(x => (chkMiddleName.Checked) ? x.MIDDLENAME : "")
.ThenBy(x => (chkPhone.Checked) ? x.PHONE_PRIMARY : "")
.ThenBy(x => (chkEmail.Checked) ? x.EMAIL1 : "").ToList();
这不是正确的订单。例如,此查询将为用户将最匹配的列行分组在顶部,然后将为另一个用户分配少量记录。我在想,可能是集团能做到这一点吗?请指导我完成这个。
(注意):列表中有额外的列我没有提及,但它们不会用于任何排序或分组。
答案 0 :(得分:0)
您可以通过
订购var sorted = list.OrderBy(l => l.FirstName).ThenBy(l => l.LastName).ThenBy(l => l.MiddleName).ToList();
答案 1 :(得分:0)
var result = list.OrderBy(t => t.FirstName).ThenBy(t => t.LastName).ThenBy(t => t.MiddleName);