Michael Weston
Michael Weston

Reputation: 387

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 :

Upvotes: 1

Views: 207

Answers (3)

Hari Prasad
Hari Prasad

Reputation: 16956

Based on your example, I assume it is not multicolumn ListBox.

Use SelectMany to flatten the hierarchy after splits.

listbox1.DataSource = File.ReadLines(filepath)
                          .SelectMany(line=>line.Split(':'));

Or, use AddRange method and do this

 ListBox1.Items.AddRange(File.ReadLines(filepath)
                             .SelectMany(line=>line.Split(':')
                             .Cast<object>()  // I think this is redundant remove if not required.
                             .ToArray()
                        );

Upvotes: 0

Kinetic
Kinetic

Reputation: 2650

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 :
}

Upvotes: 2

Slai
Slai

Reputation: 22876

list[0] is the first and list[1] the second

listbox1.DataSource = Names.Select(a => a[0]).ToArray();
listbox2.DataSource = Names.Select(a => a[1]).ToArray();

Upvotes: 0

Related Questions