1

i have an string data array which contains data like this

5~kiran
2~ram
1~arun
6~rohan

now a method returns an value like string [] data

 public string [] names()
    {
        return data.Toarray()
    }

    public class Person 
    { 
        public string Name { get; set; } 
        public int Age { get; set; } 
    }



 List<Person> persons = new List<Person>(); 
    string [] names = names();

now i need to copy all the data from an string array to an list and finally bind to grid view

gridview.datasoutrce= persons

how can i do it. is there any built in method to do it

thanks in advance

prince

3 Answers 3

6

Something like this:

var persons = (from n in names()
               let s = n.split('~')
               select new Person { Name=s[1], Age=int.Parse(s[0]) }
              ).ToList();
Sign up to request clarification or add additional context in comments.

Comments

3
var persons = names.Select(n => n.Split('~'))
                   .Select(a => new Person { Age=int.Parse(a[0]), Name=a[1] })
                   .ToList();

1 Comment

Essentially the same as Marcelo's answer.
1

Assuming that the source data are completely valid (i.e. no negative ages, names do not contain '~', every line has both age and name, and so on), here's a very easy implementation:

List<Person> persons = new List<Person>;

foreach (var s in names()) {
    var split = s.Split('~');
    int age = int.Parse (split[0]);
    string name = split[1];
    var p = new Person() { Age = age, Name = name };
    persons.Add (p);
}

You can also use a Linq query, which is shorter. See Marcelo's Answer for an example.

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.