Michael Weston Michael Weston -4 years ago 148
C# Question

How to return an access a split string while using LINQ?

I have a text file which is being read using File.ReadLines(filepath). It's filled with first and last names delimited using a :. Is there a way using LINQ in which I would be able to access the first and last name in the foreach loop for the returned datatype?

// john:doe
// david:smith
// michael:rogers

var Names = File.ReadLines(filepath)
.Select(line => line.Split(':'));

foreach (var list in Names)
listbox1.Items.Add(list); //(first name) before :
listbox2.Items.Add(list); //(last name) after :

Answer Source

Well, you're almost there. All you're missing is to get the firstName from the first item in the array and the last name in the second item.

foreach (var list in Names) 
    listbox1.Items.Add(list[0]); //(first name) before : 
    listbox2.Items.Add(list[1]); //(last name) after :
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download