0

I am trying to get values from a list. In the result I need the index of the value in the resulting list also. I dont have any idea how to get it. Can someone get me some ideas. Following is the code which i use.

        List<string> Lst1 = new List<string>();
        Lst1.Add("a");
        Lst1.Add("ab");
        Lst1.Add("c");
        Lst1.Add("d");

        List<string> result = Lst1.Select(x => x.Substring(0, 1)).ToList();
3
  • So you need index and value both in the result right ? IF that's the case you need the result as Dictionary Commented Jan 13, 2015 at 7:25
  • 1
    @CoderofCode: Not necessarily; an anonymous type might suffice as well. Depends on what they want to do with it. Commented Jan 13, 2015 at 7:26
  • Unfortunately it's not clear how you want to incorporate the original list index for the string in your result. Please edit the question so that it's clear what you're asking. Commented Jan 13, 2015 at 7:36

2 Answers 2

4

Enumerable.Select has an overload that gives the index too, so you can just use that. Note that you cannot store both the string and the index in a List<string>, so you maybe need a List<Tuple<string, int>> instead. Also note, that in a list, each element already has an index, so you don’t really need this anyway.

List<Tuple<string, int>> result = Lst1.Select(
        (x, i) => new Tuple<string, int>(x.Substring(0, 1), i)).ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

@HamletHakobyan: That'd be Tuple.Create, I guess.
@HamletHakobyan: type inference doesn't work for constructors. But, that's why Microsoft provided the Tuple.Create() methods. So Tuple.Create(x.Substring(0, 1), i) works (and IMHO is preferable to specifying the type parameters explicitly).
1

You can use second overload of Enumerable.Select:-

 var result = Lst1.Select((v, i) => new { Value = v, Index = i });

Working Fiddle Demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.