This is small post regarding How to get the index of each element in collection. There are sometime requirement to bind list of element with the dropdwon or list control with index as value and Data as Text value in this case you need to get index for each element.
Following is piece of code that make use of Linq and get the indexes for each element in collection.
Following is piece of code that make use of Linq and get the indexes for each element in collection.
//example of getting index of List Element List<string> ListItems = new List<string> { "Test1", "Test2", "Test3", "Test4" }; var ListWithIndex= someItems.Select((item, index) => new { ItemName = item, Position = index }); //example of getting index of Array Element string[] ArryItem= { "Item1", "Item2", "Item3", "Item4" }; var ArraywithInex= someItems.Select((item, index) => new { ItemName = item, Position = index });As you see in code there is one lambda function passed in the Select function of linq, and another point to note down is each elemtn has index associated with it. So by applying function like above in linq its easy to get the index of element.
No comments:
Post a Comment