2

I am new to C#, so need your help.

I have a file that has a lot of lines and 3 tab delimited fields. I want to read each line, extract the fields from the line, and push the 3 extracted values into an object. In the end, I should get an array of objects. The length of the array should be equal to the number of lines in the file. And all the information in the file should get be contained in the objects.

Eg File

abcd pqrs mnop
asdf asdf asdf
poiu poiu poiu 
xcvx xcvb rtew
: : : :
: : : :
: : : :

This is what I could come up with:


Class Definition

Class MyClass
{
   string field1;
   string field2;
   string field3;
}

Main

String[] Content = File.ReadAllLines("file.txt");

  var query = from line in Content
              let Parts = line.Split(Separators,StringSplitOptions.RemoveEmptyEntries)
                          select new MyClass
                                    {field1 = Parts[0],
                                     field2 = Parts[1],
                                     field3 = Parts[2],
                                     };

How to I get a List or IEnumerable of objects from this?

2 Answers 2

4

Your code already gives you an IEnumerable<MyClass> value (in the query variable).
If you want a list, you can call ToList() on it.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, If you can write the code for me, I'll really be grateful. What I'm not able to get is how I should execute the LINQ Query. Using a foreach?
@Deepak: The LINQ query produces an IEnumerable<T> that can be treated like any other collection. You can use a normal foreach loop.
foreach(var x in query){//x.field1,x.field2...all accessible}
Also try to avoid arrays, lists are the new arrays for C#. Check out stackoverflow.com/questions/2975426/…
1
var query = (from line in Content 
          let Parts = line.Split(Separators,StringSplitOptions.RemoveEmptyEntries) 
                      select new MyClass 
                                {field1 = Parts[0], 
                                 field2 = Parts[1], 
                                 field3 = Parts[2], 
                                 }).ToList<MyClass>();

That's it.

query will now be a List<MyClass>

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.