G. T. G. T. - 3 months ago 7
C# Question

Linq query in C# to retrieve the set of elements with respect to list

We have the list A which contain the random indexes in it. I have another list B which contains the class objects in it. I want to parse list B with the indexes present in list A and find the objects which have name Amar in it using Linq.

For example:

List<int> Indexes = new List<int>(); // This contains the random indexes
List<Student> StuObj = new List<Student>();

Class Student
{
String name;
}


Now I want to parse the list
StuObj
with the respect to the indexes present in the list
Indexes
and get the
Student
object indexes present in the list
StuObj
where the name is
Amar
.

Answer

Assuming you have two lists, List indexList and List dataList, you can use select as follows:

indexList.Select(i => dataList[i]);

You should consider what you wish to happen if indexList contains an integer < 0 or > the size of dataList. For example, you could replace invalid entries with null, like:

indexList.Select(i => i < 0 || i >= dataList.Count ? null : dataList[i]);

Or you could filter them out like:

indexList.Where(i => i>=0 && i < dataList.Count).Select(i => dataList[i]);

Or you may know via preconditions that you will never have items in the index list that are out of the range of valid values.

EDIT Based on the updated question, try this:

dataList.Where((item, index) => indexList.Contains(index) && item.Name == "Amar")
    .Select(item => dataList.IndexOf(item));

This takes advantage of the Select and Where overloads that take the index of the item. The Where clause selects the item where the item's index in dataList is in the indexList, and also where the item's Name is Amar. The Select clause then returns the index of the item in the original data list.

Comments