English 中文(简体)
我如何利用林克从一系列指数到收集物体?
原标题:How can I use linq to go from an array of indices to a collection of objects?

我的题目是一个含糊不清的问题,因为它很难问,但我的情况是:

我有一系列的斜体,它们是单独收集物体的指数。

阵列希望:

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

这些指数中每个指数都与我所收集的该指数中的一个目标相对应。

我希望能够利用我阵列中的指数,对这些物体进行新的收集。

我如何利用一些准则职能?

最佳回答
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);
}

当然,你收集物体的情况也发生了变化。

问题回答

与此类似:

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();

您在收集各项指数时的基本情况是,你正在利用索引员预测在<代码><>>项目/代码>收集(无论这些项目类型如何)中的相应项目。

如果您的目标收集只是一个< 编码>,即可计算和参照;SomeType>,而不是一个索引: ElementAt():

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签