Reputation: 789
I have a List of String[], which I am trying to convert to a dataset/datatable using LINQ. I parsed the text file to list, in which the first row has 4 columns and others have data associated with columns.
Everything comes up as an array in the list.
List[10] where List [0] has string[4] items.
List<string[]> list = File.ReadLines(s)
.Select(r => r.TrimEnd('#'))
.Select(line => line.Split(';'))
.ToList();
DataTable table = new DataTable();
table.Columns.AddRange(list.First().Select(r => new DataColumn(r.Value)).ToArray());
list = list.Skip(1).ToArray().ToList();
list.ForEach(r => table.Rows.Add(r.Select(c => c.Value).Cast<object>().ToArray()));
The LINQ doesn't accept the Value property.
Can some one suggest the simple and efficient way for this implementation?
Upvotes: 0
Views: 5868
Reputation: 37059
System.String
doesn't have a property named Value
.
If you want to create a column for each item in the first row, just give it the strings:
table.Columns.AddRange(list.First().Select(r => new DataColumn(r)).ToArray());
// You don't need ToArray() here.
list = list.Skip(1).ToList();
// Get rid of Value in this line too, and you don't need
// .Select(c => c) either -- that's a no-op so leave it out.
list.ForEach(row => table.Rows.Add(row.Cast<object>().ToArray()));
There's no Dictionary here. list.First()
is an array of strings. When you call Select
on an array, it just passes each item in the array to the lambda in turn.
Dictionary<TKey,TValue>.Select()
passes the lambda a series of KeyValuePair<TKey, TValue>
. Different class, different behavior.
Upvotes: 2