Hi all,
I have to parse a .txt file and retrieve only "Name" from second
column and store it in a list
My text file is of this format:
Bit Name Description
-1 Lucky groupa
-1 Roy groupb
In the list i should have only "Lucky" and "Roy" and nothing else.
I am very new to C# can anyone please tellme how i can do this
thanks for help,
Nithin
I
This is actually pretty simple depending, but we need a little more
information. Is Bit always a -1 or a 0 or...always an integral value? Is
Name always a single word? Is Name ever surrounded with quotes? Could
there be any types of delimiters besides a space?
From the simple example you gave, you simply have 3 columns delimited by a
space...:
If you are using .Net 3.5, you can make use of anonymous types and LINQ
(note, I know this is definitely not the most efficient block of code in the
world, but hey, it works
string[] lines = File.ReadAllLines(@"C:\input.txt");
int i = 0;
var items =
from line in lines
where i++ != 0
select new {
Bit = line.Split(new char[] { ' ' }, 3)[0],
Name = line.Split(new char[] { ' ' }, 3)[1],
Description = line.Split(new char[] { ' ' }, 3)[2]
};
foreach (var item in items) {
Console.WriteLine(
"Bit: {0}, Name: {1}, Description: {2}",
item.Bit,
item.Name,
item.Description
);
}
// The following can be used in version 2.0 and does not make use of
anonymous types nor LINQ:
string[] lines = File.ReadAllLines(@"C:\input.txt");
int i = 0;
foreach (string line in lines) {
if (i++ == 0) continue;
string[] items = line.Split(new char[] { ' ' }, 3);
Console.WriteLine(
"Bit: {0}, Name: {1}, Description: {2}",
items[0], items[1], items[2]
);
}
HTH,
Mythran