【问题标题】:Create full set from a list with missing keys in C# [closed]从 C# 中缺少键的列表创建完整集 [关闭]
【发布时间】:2020-09-16 01:14:20
【问题描述】:

我已经进行了很多挖掘,但似乎无法找到这个特定问题的答案;类似问题的答案,但与此完全不同。

基本上,我想要做的是在列表中添加缺少默认值的键。我有一个具有以下结构的 List>():

键:值

a : Apple
b : Orange
c : Mango
b : Lime
c : Lemon
a : Berry
d : Carrot

从上面的列表中,我想创建一个完整的集合,其中缺少键。
预期产出

预期键:值

a : Apple
b : Orange
c : Mango
d : ""
a : ""
b : Lime
c : Lemon
d : ""
a : Berry
b : ""
c : ""
d : Carrot

是否有可能使用 C# 以表演的方式做到这一点?

【问题讨论】:

  • 您是否可能忘记提及某种序列逻辑?您的密钥似乎被多次使用。
  • “更快”是什么意思?
  • 我猜海登已经理解了这个问题。这是一个使用 C# 问题的列表操作,不需要任何序列逻辑。

标签: c# .net list linq key-value


【解决方案1】:

给定

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

【讨论】:

  • 谢谢,海登,非常接近。但它不适用于以下数据: a : Apple b : Orange c : Mango a : Berry b : Plum
  • 如果最后一个键不存在,它会忽略它并且不放置空值。例如a : 苹果 b : 橙 c : 芒果 a : 浆果也不行
  • @DaemonBee 查看我的编辑。
  • @DaemonBee 需要更多关于它为什么不起作用的信息。
  • @DaemonBee 上面发布的代码适用于用例。您需要手动定义 distinctKeys 或使用自定义比较器更改 distinctKeys 订单的原始代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-01
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 2021-01-25
  • 2016-07-25
相关资源
最近更新 更多