I have two list, one contains string data and the second one contains some index numbers.
List<int> myIndexList = new List<int>() {4, 3, 1, 2, 5, 0};
List<string> myValuesList = new List<string>()
{"Value 1", "Value 2", "Value 3", "Value 4", "Value 5", "Value 6"};
and my result must be
Value 5 Value 4 Value 2 Value 3 Value 6 Value 1
how I can do in the most efficient way? Because these lists may contain many items
I think you just want:
var orderedByIndexList = myIndexList.Select(index => myValuesList[index]);
If you need it as a List<T>
, put .ToList()
at the end.
Note that this doesn't modify myValuesList
- it just creates a new sequence in the appropriate order. It's also fine for myIndexList
to be incomplete, or to contain duplicates: you'll end up with "missing" or "duplicate" values from myValuesList
in the output.
See more on this question at Stackoverflow