简体   繁体   English

从列表中选择项目与保存在其他列表中的索引有关?

[英]select items from a list relate to indexes saved in other list?

i have: 我有:
a list of list x; 清单x的清单;
a list of list A that contains indexces of some elements in list d as A[i]= [1,3] 列表A的列表,其中包含列表d中某些元素的索引,如A [i] = [1,3]
a list of list d that contains values as d[i]=[500,200,1000, 40,60,..] 包含值d [i] = [500,200,1000,40,60,..]的列表d的列表
i want to select from d elements which has the indexes saved in A and add them to x 我想从已将索引保存在A中的d个元素中进行选择,并将它们添加到x中
then x[0] will = [200,40] 那么x [0]将= [200,40]

i use this code: 我使用此代码:

List<int> sublist = new List<int>();
for (int b = 0; b < A[i1].Count(); b++)
{
    sublist .Add(d[i1][A[i1][b]]);
 }
x.Add(sublist );

can you help me to do it with an efficient methode? 您能帮我用一种高效的方法吗?

List<int> sublist = new List<int>();
foreach(int i in A)
{
    sublist.Add(d[i]);
}
x.Add(sublist);

It really depends what you mean by "efficient". 这实际上取决于您所说的“有效”。

If you want the fastest execution time, then nested for loops will probably be your best bet. 如果您想要最快的执行时间,那么嵌套for循环可能是您的最佳选择。 You might be able to save some time by specifying the initial size for sublist to match the number of elements in A[i1] , and by dropping the .Count() extension method in favour of the .Count or .Length property, depending on the precise types you're using. 您可能能够通过指定的初始大小,以节省一些时间sublist以匹配元素的数量A[i1]并通过降低.Count()赞成的扩展方法.Count.Length属性,这取决于您使用的确切类型。

If you just want simple code, then LINQ can help: 如果您只需要简单的代码,那么LINQ可以帮助您:

List<List<int>> x = A
    .Select((value, index) => value.Select(i => d[index][i]).ToList())
    .ToList();

Demo 演示版

Or: 要么:

List<List<int>> x = A
    .Zip(d, (ai, di) => ai.Select(i => di[i]).ToList())
    .ToList();

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM