1

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 :
1
  • Is it mullti column ListBox ? Commented Aug 26, 2016 at 2:22

3 Answers 3

2

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 :
}
Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

0

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()
                        );

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.