【问题标题】:Select -> Refer to itself (currently created list)选择 -> 引用自身(当前创建的列表)
【发布时间】:2018-01-05 23:39:03
【问题描述】:

有没有办法在创建时(在方法内部)引用由Select 方法创建的List (IEnumerable)

我有一个看起来像这样的字典:

Dictionary<char, char> d = new Dictionary<char, char>() 
{ 
  {'a', 'b'},
  {'b', 'a'},
  {'c', 'd'},
  {'d', 'c'},
  //...
};

它通过string.Join("", d.Select(...)) 转换为字符串。 字典中的重复值(ab 和 ba)被整理出来。 我试过这个:

                                   //Checks for an earlier swapped duplicate........If not, select it
d.Select(x => !enumerable.Contains(x.Value.ToString() + x.Key.ToString()) ? x.Key.ToString() + x.Value.ToString() : string.Empty);

这里,“可枚举”指的是列表,它是由 Select 方法创建的,但我还没有找到这样做的方法。

预期的最终结果应如下所示:"abcd" 而不是 "abbacddc" 就像只连接键和值。

我可以用 for 循环解决这个问题,但这需要额外的代码..

【问题讨论】:

    标签: c# list linq dictionary select


    【解决方案1】:

    不,但您可以使用AggregateDistinct

    var enumerable = d.Aggregate(string.Empty,
        (acc, kv) => string.Concat(acc,
                                   kv.Key,
                                   kv.Value))
                      .Distinct();
    

    enumerable 将是具有所需输出的IEnumerable&lt;char&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 2015-10-12
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      相关资源
      最近更新 更多