LINQ,对 IEnumerable 进行分组

发布于 2024-11-28 17:14:40 字数 280 浏览 0 评论 0 原文

我有以下元素(可能超过两个):

new[] { new[] { "A" }, new[] { "B", "C" } }
new[] { new[] { "D" }, new[] { "E", "F" } }

我想将它们分组如下:

“A”,“D”

“B”,“C”,“E”,“F”

什么是最优化的方式(或者至少是一个好方法)?

是否可以以某种方式存储第一对“D”(以及第二对 E”和“F”)一开始不在同一个数组中?

I have the following elements (could be more than two):

new[] { new[] { "A" }, new[] { "B", "C" } }
new[] { new[] { "D" }, new[] { "E", "F" } }

I want to group them as follow:

"A", "D"

"B", "C", "E", "F"

What is the most optimum way (or at least a good way)?

Is it possible to store, somehow, that on the first pair "D" (and on second pair E" and "F") were not in the same array at the beginning?

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

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

发布评论

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

评论(2

静待花开 2024-12-05 17:14:40

我昨天刚遇到这个。不是最具可读性,但它实现了目标。

new [] { 
    new[] { new[] { "A" }, new[] { "B", "C" } },
    new[] { new[] { "D" }, new[] { "E", "F" } }
}.SelectMany((x, arrayPos) => x.Select((y, itemPos) => new { y, arrayPos, itemPos }))
    .GroupBy(x => new { x.itemPos })
.Select(x => x.SelectMany(y => y.y.Select(z => new { z, y.arrayPos })))

arrayPos 值将指示原始位置。

I just ran into this yesterday. Not the most readable, but it accomplishes the objective.

new [] { 
    new[] { new[] { "A" }, new[] { "B", "C" } },
    new[] { new[] { "D" }, new[] { "E", "F" } }
}.SelectMany((x, arrayPos) => x.Select((y, itemPos) => new { y, arrayPos, itemPos }))
    .GroupBy(x => new { x.itemPos })
.Select(x => x.SelectMany(y => y.y.Select(z => new { z, y.arrayPos })))

The arrayPos value will indicate the original position.

心如狂蝶 2024-12-05 17:14:40

假设集合中有这两个:

var collections = new[]
{
    new[] { new[] { "A" }, new[] { "B", "C" } },
    new[] { new[] { "D" }, new[] { "E", "F" } }
};

var result = from first in collections
             from second in first.Select((x, i) => new {x, i})
             from third in second.x
             group third by second.i;

结果是 IEnumerable>,这意味着每个成员都是 string 的集合,并且还具有一个 int 键。请注意,结果可能未排序,因此 1 的组可能排在第一位。如果您不希望这样做,请将 orderby 添加到查询末尾。

Assuming you have the two in a collection:

var collections = new[]
{
    new[] { new[] { "A" }, new[] { "B", "C" } },
    new[] { new[] { "D" }, new[] { "E", "F" } }
};

var result = from first in collections
             from second in first.Select((x, i) => new {x, i})
             from third in second.x
             group third by second.i;

The result is IEnumerable<IGrouping<int, string>>, which means each member is a collection of strings that also has an int key. Note that the result may not be sorted, so the group for 1 may come first. If you don't want that, add orderby to the end of the query.

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