我有一个名称列表,我需要按字母顺序对其进行排序,但是它没有按预期排序,只能将相似的字母组合在一起。
这是我的代码
[Route("api/getdeptemployee/{Id}")]
[HttpGet]
public IActionResult GetDepartmentEmp(int Id)
{
var item = (from o in db.Employee
join a in db.Department on o.DepartmentId equals a.Id
where a.Id == Id
select new
{
Id = o.Id,
LastName = o.LastName,
AddedBy = o.LastName + " " + o.FirstName
}).OrderBy(s => s.LastName).ToList();
return Json(item);
}
这是结果
{
"id": 2277,
"lastName": " IBIRONKE",
"addedBy": " IBIRONKE ABIMBOLA "
},
{
"id": 2278,
"lastName": " IGBINOBA",
"addedBy": " IGBINOBA PATRICIA"
},
{
"id": 2279,
"lastName": " IRUBOR",
"addedBy": " IRUBOR CATHERINE "
},
{
"id": 2276,
"lastName": " KOLAWOLE",
"addedBy": " KOLAWOLE SEGUN"
},
{
"id": 2281,
"lastName": " LAMPTEY",
"addedBy": " LAMPTEY JOSEPH"
},
{
"id": 2282,
"lastName": " OJEDIRAN",
"addedBy": " OJEDIRAN OLUWASEYI "
},
{
"id": 2283,
"lastName": "ADEBANJO",
"addedBy": "ADEBANJO ABAYOMI "
},
{
"id": 2296,
"lastName": "ADENIYI",
"addedBy": "ADENIYI ONI"
},
{
"id": 2284,
"lastName": "ADEPOJU",
"addedBy": "ADEPOJU ABAYOMI "
},
{
"id": 2297,
"lastName": "AFOLABI-ONI",
"addedBy": "AFOLABI-ONI OLUFUNKE "
},
{
"id": 2285,
"lastName": "AGBOM",
"addedBy": "AGBOM MAURICE"
},
{
"id": 2293,
"lastName": "AKPU-AGBAKA",
"addedBy": "AKPU-AGBAKA BYRON"
},
{
"id": 2286,
"lastName": "ASUQUO",
"addedBy": "ASUQUO NAOMI "
},
{
"id": 2299,
"lastName": "AYI-SAMUEL",
"addedBy": "AYI-SAMUEL BLESSING"
},
{
"id": 2298,
"lastName": "ECHEBIRI",
"addedBy": "ECHEBIRI JUSTINE"
},
{
"id": 2287,
"lastName": "EDET ",
"addedBy": "EDET NSIKAK "
},
{
"id": 2292,
"lastName": "EZE",
"addedBy": "EZE FAVOUR "
},
{
"id": 2289,
"lastName": "JABE",
"addedBy": "JABE AJOM"
},
{
"id": 2288,
"lastName": "MADUNECHE",
"addedBy": "MADUNECHE CHIDI "
},
{
"id": 2280,
"lastName": "MUSTAPHA",
"addedBy": "MUSTAPHA TRACY "
},
{
"id": 2274,
"lastName": "OLAWOYIN",
"addedBy": "OLAWOYIN KELECHI "
},
{
"id": 2290,
"lastName": "ONAA",
"addedBy": "ONAA JAMES "
},
{
"id": 2275,
"lastName": "SORINWA",
"addedBy": "SORINWA OLUFUNKE "
},
{
"id": 2295,
"lastName": "UGBE",
"addedBy": "UGBE JOHN-PAUL"
},
{
"id": 2294,
"lastName": "UWAH",
"addedBy": "UWAH FRANCIS"
},
{
"id": 2291,
"lastName": "ZOCLI",
"addedBy": "ZOCLI ANDREW"
}
它没有按字母顺序排序,请如何解决此问题。有没有办法让我按字母顺序从A-Z开始?谢谢
答案 0 :(得分:1)
Aleks Andreev 在评论中指出
尝试从姓氏中切出空格,例如OrderBy(s => s.LastName.Trim())
答案 1 :(得分:0)
我看到您数据中的某些字符串开头有一个空格。您可能需要在对字符串进行排序和返回之前先修剪掉它们。
此外,在LINQ中对对象进行排序是区分大小写的,这也可能会受到数据库中数据的影响。由于您仍在使用LINQ to SQL(根据Panagiotis的评论),因此您可以跳过ToLower()
调用并依靠数据库支持。
这是修复代码的方式,以便以不区分大小写的方式修剪和排序数据(注意对Trim和ToLower的调用):
[Route("api/getdeptemployee/{Id}")]
[HttpGet]
public IActionResult GetDepartmentEmp(int Id)
{
var item = (from o in db.Employee
join a in db.Department on o.DepartmentId equals a.Id
where a.Id == Id
select new
{
Id = o.Id,
LastName = o.LastName.Trim(),
AddedBy = o.LastName.Trim() + " " + o.FirstName.Trim()
}).OrderBy(s => s.LastName.ToLower()).ToList();
return Json(item);
}