如果我的收藏品如下:
var list = new List<string>()
{
"one",
"one",
"two",
"two",
"three"
};
是否可以使用linq获得如下结果?
“one-1”,“one-2”,“two-1”,“two-2”,“three”
我正在尝试获取重复值并将连续数字附加到它们以使其唯一
| EDIT
我在LinqPad做过这个,似乎没错......
Dictionary<string,string> names = new Dictionary<string,string>(){
{"val1","text1"},
{"val2","text1"},
{"val3","text2"},
{"val4","text3"},
{"val5","text3"}
};
var filteredNames = names.GroupBy (x => x.Value).ToDictionary(x => x.Key, x => x.Select((i, index) => i.Value + index.ToString()));
建议欢迎!
答案 0 :(得分:1)
从列表开始,您应该执行以下操作:
var filteredNames = list.GroupBy (x => x).SelectMany((i, index) => i.Value + "-" + index.ToString());
从字典开始,你的解决方案是正确的,但如果你想要一个列表,你应该做如下:
var filteredNames = names.GroupBy (x => x.Value).SelectMany((i, index) => i.Value + "-" + index.ToString());