C# - 组合集合问题

发布于 2024-10-27 06:23:37 字数 637 浏览 4 评论 0 原文

如果我有一个 IDictionary,是否可以接收一个 IEnumerable,它 将包含每个 KeyValuePair 分解为两个相继插入的 (int, int) 条目?

小例子:

Dictionary:
5 - 25
6 - 36
7 - 49

Wanted Enumerable:
5, 25, 6, 36, 7, 49

另外,我想把它放在一个超级漂亮的声明中,但我想不出一个合适的声明:)


更新:

LINQ 是否允许在每个 .Select 语句中插入多个元素,共享以下想法:

xyz.Select(t => (t, null))

以便生成的 Enumerable 将包含紧随其后的是 tnull 吗?

If I have a IDictionary<int, int>, is it possible to receive a IEnumerable<int>, which
would contain every KeyValuePair<int, int> disassembled into two (int, int) entries inserted one after another?

Small example:

Dictionary:
5 - 25
6 - 36
7 - 49

Wanted Enumerable:
5, 25, 6, 36, 7, 49

Also, I wanted to have this in one super-pretty statement, but I couldn't think of an appropriate one :)


Update:

Does LINQ allow to insert more than one element per .Select statement, something sharing the idea of:

xyz.Select(t => (t, null))

so that the resulting Enumerable would contain both t and null right after it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

囍笑 2024-11-03 06:23:37

您可以使用 SelectMany(IEnumerable, Func)(加上重载)。这是一个示例

var dict = new Dictionary<int, int> {
   { 5, 25 },
   { 6, 36 },
   { 7, 49 } 
}; 

var projection = dict.SelectMany(kv => new[] { kv.Key, kv.Value });

根据评论,这只是实现您所要求的目标的一种方法。

You could use SelectMany<TSource, TResult>(IEnumerable<TSource>, Func<TSource, IEnumerable<TResult>>) (plus overloads). Here's an example

var dict = new Dictionary<int, int> {
   { 5, 25 },
   { 6, 36 },
   { 7, 49 } 
}; 

var projection = dict.SelectMany(kv => new[] { kv.Key, kv.Value });

As per the comments, this is just one way of achieving what you have asked.

恍梦境° 2024-11-03 06:23:37

您可以创建一个方法,以您想要的方式将字典分解为 IEnumerable。

using System.Collections.Generic;
using System;

public class C {

    public static void Main()
    {
        var dic = new Dictionary<int,int>();
        dic[0] = 1;
        dic[2] = 3;
        dic[4] = 5;

        foreach (var i in Decompose(dic))
            Console.WriteLine(i);

        Console.ReadLine();
    }

    public static IEnumerable<int> Decompose(IDictionary<int,int> dic)
    {
        foreach (var i in dic.Keys)
        {
            yield return i;
            yield return dic[i];
        }
    }
}

输出:

  0
  1
  2
  3
  4
  5

You could create a method that will decompose your dictionary into an IEnumerable in the way you want.

using System.Collections.Generic;
using System;

public class C {

    public static void Main()
    {
        var dic = new Dictionary<int,int>();
        dic[0] = 1;
        dic[2] = 3;
        dic[4] = 5;

        foreach (var i in Decompose(dic))
            Console.WriteLine(i);

        Console.ReadLine();
    }

    public static IEnumerable<int> Decompose(IDictionary<int,int> dic)
    {
        foreach (var i in dic.Keys)
        {
            yield return i;
            yield return dic[i];
        }
    }
}

Output:

  0
  1
  2
  3
  4
  5
北陌 2024-11-03 06:23:37

我之所以这么想,是因为

var enumerable = Mix(dict.Keys, dict.Values);

我相信 .NET Framework 4.0 Enumerable.Zip 已经接近[1],

所以我找到了时间来实现这个MixSequences 方法,请注意,我只是为了好玩使其成为n元,因此它将组合任意数量的序列(不仅仅是2个)。

using System;
using System.Linq;
using System.Collections.Generic;

namespace NS
{
    static class Program
    {
        private static IEnumerable<T> MixSequences<T> (params IEnumerable<T>[] sequences)
        {
            var se = sequences.Select(s => s.GetEnumerator()).ToList();
            try
            {
                while (se.All(e => e.MoveNext()))
                    foreach (var v in se.Select(e => e.Current))
                        yield return v;
            }
            finally
            { se.ForEach(e => e.Dispose()); }
        }

        public static void Main(string[] args)
        {
            var dict = new Dictionary<int,int>{ {1,4},{13,8},{2,1} };
            var twin = new Dictionary<int,int>{ {71,74},{83,78},{72,71} };

            Console.WriteLine("Keys: {0}", string.Join(", ", dict.Keys));
            Console.WriteLine("Values: {0}", string.Join(", ", dict.Values));
            Console.WriteLine("Proof of pudding: {0}", string.Join(", ", MixSequences(dict.Keys, dict.Values)));
            Console.WriteLine("For extra super fun: {0}", string.Join(", ", MixSequences(dict.Keys, twin.Keys, dict.Values, twin.Values)));
        }
    }
}

干杯

[1]更新请参阅此处此处此处了解背景。

I'd think of this as

var enumerable = Mix(dict.Keys, dict.Values);

I believe in .NET framework 4.0 Enumerable.Zip comes close[1]

So I've found time to implement thisMixSequences method, Note how just for fun I made it n-ary, so it will combine any number of sequences (not just 2).

using System;
using System.Linq;
using System.Collections.Generic;

namespace NS
{
    static class Program
    {
        private static IEnumerable<T> MixSequences<T> (params IEnumerable<T>[] sequences)
        {
            var se = sequences.Select(s => s.GetEnumerator()).ToList();
            try
            {
                while (se.All(e => e.MoveNext()))
                    foreach (var v in se.Select(e => e.Current))
                        yield return v;
            }
            finally
            { se.ForEach(e => e.Dispose()); }
        }

        public static void Main(string[] args)
        {
            var dict = new Dictionary<int,int>{ {1,4},{13,8},{2,1} };
            var twin = new Dictionary<int,int>{ {71,74},{83,78},{72,71} };

            Console.WriteLine("Keys: {0}", string.Join(", ", dict.Keys));
            Console.WriteLine("Values: {0}", string.Join(", ", dict.Values));
            Console.WriteLine("Proof of pudding: {0}", string.Join(", ", MixSequences(dict.Keys, dict.Values)));
            Console.WriteLine("For extra super fun: {0}", string.Join(", ", MixSequences(dict.Keys, twin.Keys, dict.Values, twin.Values)));
        }
    }
}

Cheers

[1] Update See here, here or here for background.

囚你心 2024-11-03 06:23:37

尝试使用以下方法:

var list = dictionary.Keys.ToList();
var list2 = dictionary.Values.ToList();

您可以将这个列表合二为一。

try to use following methods:

var list = dictionary.Keys.ToList();
var list2 = dictionary.Values.ToList();

you can join this lists in one.

病毒体 2024-11-03 06:23:37

您可以使用 LINQ 创建对象/集合/您拥有的东西。假设您想将两个非常不同/不相关(或几乎不相关)的项目合并为一个(伪代码如下):

List<KeyValuePair<string, string>> newList = (from a in AList
                                              select new KeyValuePair<string, string> 
                                              {
                                                a,
                                                getBfromA(a)
                                              });

You can create a object/collection/what have you using LINQ. Say you want to merge two very different/unrelated (or barely related) items into one (pseudo code follows):

List<KeyValuePair<string, string>> newList = (from a in AList
                                              select new KeyValuePair<string, string> 
                                              {
                                                a,
                                                getBfromA(a)
                                              });
缺⑴份安定 2024-11-03 06:23:37

dict.Select(d => new[] { d.Key, d.Value }).SelectMany(d => d)

dict.Select(d => new[] { d.Key, d.Value }).SelectMany(d => d)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文