我正在使用带有cId
(课程 ID)和cName
(课程名称)的 DropDownList 。但是,如果有一个重复的cName
,我想加入startDate
用cName
。喜欢:$"cName ({startDate})"
这是我的列表的样子:
var list = new List<(int cId, string cName, string startDate)>
{
(1, "Math", "1/12"),
(2, "Music", "1/12"),
(3, "English", "1/12"),
(4, "English", "11/4"),
(5, "Swedish", "1/12"),
(6, "Russia", "1/12")
};
由于有两个 cName
英文, startDate
应该添加到它的字符串中,例如:
cId cName
---- -----
1 | "Math"
2 | "Music"
3 | "English (1/12)"
4 | "English (11/4)"
6 | "Swedish"
7 | "Russia"
我想到的是:
如果列表有任何重复cName
,cName = $"cName ({startDate})"
编辑:
这是将列表添加到 DropDownList 的方式:
foreach (var item in list)
{
dplCourse.Items.Add(new ListItem(item.cId, item.cName));
}
在将它们添加到显示列表之前,您需要遍历列表以查找哪些是重复项并更改重复项的名称。
var list = new List<(int cId, string cName, string startDate)>
{
(1, "Math", "1/12"),
(2, "Music", "1/12"),
(3, "English", "1/12"),
(4, "English", "11/4"),
(5, "Swedish", "1/12"),
(6, "Russia", "1/12")
};
var duplicates = new HashSet<string>(
list.GroupBy(x => x.cName) //Group the items by name
.Where(g => g.Count() > 1) //Find groups with more than 1
.Select(g => g.Key)); //Just add the names to the HashSet, not the group
foreach (var item in list)
{
var displayName = item.cName
if(duplicates.Contains(displayName))
{
displayName += $" ({item.startDate})";
}
dplCourse.Items.Add(new ListItem(item.cId, displayName));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句