如何使用 linq 从索引数组转换为对象集合?

发布于 2024-12-05 01:57:02 字数 289 浏览 2 评论 0原文

我的标题问题有点模糊,因为很难问,但我的情况是这样的:

我有一个整数数组,它们是单独的对象集合的索引。

该数组如下所示:

int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ };

每个索引都对应于我拥有的集合中该索引处的一个对象。

我希望能够使用数组中的索引构建这些对象的新集合。

我该如何使用一些 LINQ 函数来做到这一点?

My title question is a little vague, since it's hard to ask, but my situation is this:

I have an array of ints, which are indices into a separate collection of objects.

The array looks like this:

int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ };

Each of these indices corresponds to an object at that index in a collection I have.

I want to be able to build a new collection of these objects using the indices in my array.

How would I do that using some LINQ functions?

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

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

发布评论

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

评论(2

落叶缤纷 2024-12-12 01:57:02
int[] indices = { 0, 2, 4, 9, 10, 11, 13 };
string[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q" };

IEnumerable<string> results = indices.Select(s => strings[s]);

// or List<string> results = indices.Select(s => strings[s]).ToList();

foreach (string result in results) // display results
{
    Console.WriteLine(result);
}

当然,将字符串等更改为您的对象集合。

int[] indices = { 0, 2, 4, 9, 10, 11, 13 };
string[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q" };

IEnumerable<string> results = indices.Select(s => strings[s]);

// or List<string> results = indices.Select(s => strings[s]).ToList();

foreach (string result in results) // display results
{
    Console.WriteLine(result);
}

Of course change strings etc to your collection of objects.

埋葬我深情 2024-12-12 01:57:02

像这样的东西应该有效:

List<int> items = Enumerable.Range(1,100).ToList();
int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ };
var selectedItems = indices.Select( x => items[x]).ToList();

基本上,对于索引集合中的每个索引,您都使用索引器将其投影到 items 集合中的相应项目(无论这些项目是什么类型)。

如果您的目标集合只是 IEnumerable,那么您也可以使用 ElementAt() 而不是索引器:

var selectedItems = indices.Select(x => items.ElementAt(x)).ToList();

Something like this should work:

List<int> items = Enumerable.Range(1,100).ToList();
int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ };
var selectedItems = indices.Select( x => items[x]).ToList();

Basically for each index in your collection of indices you are projecting to the corresponding item in your items collection (whatever type those items are) using the indexer.

If your target collection is just an IEnumerable<SomeType> than you can alternatively use ElementAt() instead of an indexer:

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