给定
var list = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("a", "Apple"),
new KeyValuePair<string, string>("b", "Orange"),
new KeyValuePair<string, string>("c", "Mango"),
new KeyValuePair<string, string>("b", "Lime"),
new KeyValuePair<string, string>("c", "Lemon"),
new KeyValuePair<string, string>("a", "Berry"),
new KeyValuePair<string, string>("d", "Carrot"),
};
通过执行以下操作,我们可以使用 for 循环轻松完成此操作。下面将获取列表中的不同键。
var distinctKeys = list
.Select(pair => pair.Key)
.Distinct()
.OrderBy(pair => pair)
.ToArray();
如果您想直接硬编码 distinctKeys 并节省计算不同键的时间,您可以执行以下操作:
var distinctKeys = new[] {"a", "b", "c", "d"};
如果需要填写键,以下循环将在给定索引处插入对。
var lastKeyIndex = -1;
for (var index = 0; index < list.Count; index++)
{
var currentKeyIndex = lastKeyIndex + 1 == distinctKeys.Length ? 0 : lastKeyIndex + 1;
var currentKey = distinctKeys[currentKeyIndex];
if (list[index].Key != currentKey)
{
list.Insert(index, new KeyValuePair<string, string>(currentKey, string.Empty));
}
lastKeyIndex = currentKeyIndex;
}
for (var index = lastKeyIndex; index < distinctKeys.Length; index++)
{
list.Add(new KeyValuePair<string, string>(distinctKeys[index], string.Empty));
}
输出
a : Apple
b : Orange
c : Mango
d :
a :
b : Lime
c : Lemon
d :
a : Berry
b :
c :
d : Carrot