gpt4 book ai didi

c# - 对包含两个项目的列表进行排序并在 C# 中转换为大写的错误结果

转载 作者:行者123 更新时间:2023-12-05 09:25:46 25 4
gpt4 key购买 nike

我有一个名为 person 的类,其中包含 id 和 name。我有一个 person 列表。我想按 Id 对列表排序。然后,将那些相同 ID 按名称排序并将名称转换为大写字母,最后删除重复项。

List<person> list = new List<person>();
list.Add(new person(112, "Bname"));
list.Add(new person(111, "Cname"));
list.Add(new person(112, "Aname"));
list.Add(new person(111, "Aname"));
list.Add(new person(114, "Aname"));

期望的输出:

111,ANAME
111,CNAME
112,ANAME
112,BNAME
114,ANAME

我的代码:

       for (int i = 0; i < list.Count - 1; i++)
{

if (list[i + 1].Id < list[i + 1].Id && string.Compare(list[i + 1].Name, list[i + 1].Name) > 0)
{
person temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
i = -1; //sort from lowest out of order index
}
}

for (int i = 0; i < list.Count - 1; i++)
{
list[i].Name= list[i].Name.ToUpper();
if (list[i] == list[i + 1])
list.Remove(list[i + 1]);
}

但是结果是错误的。有人可以帮助我吗?

最佳答案

您可以使用 linq 轻松完成这一切.

1- 使用 OrderBy(x => x.Id 以 Id 排序列表

2- 使用 ThenBy(x=>x.Name) 按名称对具有相同 ID 的那些进行排序

3- 使用 .Select(x=>new {Id=x.Id,Name= x.Name.ToUpper()}) 将名称转换为大写

4- 使用 .Distinct() 删除重复项

  var result=list.OrderBy(x => x.Id).ThenBy(x=>x.Name)
.Select(x=>new {Id=x.Id,Name= x.Name.ToUpper()}).Distinct().ToList();

关于c# - 对包含两个项目的列表进行排序并在 C# 中转换为大写的错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75070341/

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