我有一个带冒号分隔值的简单List<string>
。
示例
name:john
surname:michael
gender:boy
name:pete
title:captain
会变成
surname:michael
gender:boy
name:pete
title:captain
答案 0 :(得分:8)
list = list.GroupBy(s => s.Split(':')[0].ToLower())
.Select(g => g.Last())
.ToList();
答案 1 :(得分:0)
一般来说:使用字典 - &gt;你正在使用List AS作为字典。
我更喜欢LazyDictionarys,你可以在不检查密钥存在的情况下更新,但是对于伪代码的标准.Net Dict
dict = new Dictionary()
for each item in your_LIST
{
tmp = item.Split(':')
if dict.ContainsKey(tmp[0])
{
dict[tmp[0]] = tmp[1]
}
else
{
dict.Add(tmp[0],tmp[1])
}
}
你有一本字典,这就是你想要的,如果你真的想把它传回一个列表然后很好,但实际上你可能希望这是一本字典'一直向下'
答案 2 :(得分:0)
它可以是使用linq的锥形
private string[] inputs = new string[]
{
"name:john",
"surname:michael",
"gender:boy",
"name:pete",
"title:captain",
};
private string[] expected = new string[]
{
"surname:michael",
"gender:boy",
"name:pete",
"title:captain",
};
private static List<string> FilterList(IEnumerable<string> src) {
return src.Select(s =>
{
var pieces = s.Split(':');
return new {Name = pieces[0], Value = pieces[1]};
}).GroupBy(m => m.Name)
.Select(g => String.Format("{0}:{1}", g.Key, g.Last().Value)).ToList();;
}
[TestMethod]
public void TestFilter() {
var actual = FilterList(inputs);
CollectionAssert.AreEquivalent(expected, actual);
}