List<byte[]> data = new List<string>(File.ReadAllLines(Filename)).ConvertAll<byte[]>(delegate(string value)
{
return new List<string>(value.Split('.')).ConvertAll<byte>(delegate(string byteVal)
{
return Convert.ToByte(byteVal);
}).ToArray();
});
views:
131answers:
2
+2
A:
Extension methods are often more succinct than the equivalent LINQ:
File.ReadAllLines(Filename).Select(
line => line.Split('.').Select(ch => Convert.ToByte(ch)).ToArray()
).ToArray();
In LINQ, this would be:
(from line in File.ReadAllLines(Filename)
select (
from ch in line.Split('.')
select Convert.ToByte(ch)
).ToArray()
).ToArray()
I don't have VS in front of me, so I hope this isn't too far off the mark. Both versions require VS9 (2008) of course.
Marcelo Cantos
2009-12-20 12:09:20
`The type arguments for method 'System.Linq.Enumerable.Select<TSource,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.`. This works better: `.Select(token => Convert.ToByte(token))`, but is not different enough from your answer to justify another answer :P
Kobi
2009-12-20 12:18:49
Thanks for the correction, Kobi. I've changed the answer.
Marcelo Cantos
2009-12-20 12:27:04
thanks. much appreciated.
adge
2009-12-20 14:18:43
+1
A:
Well, I would typically consume the input a line at a time (to allow large files to be processed):
static IEnumerable<string> ReadLines(string path) {
using (var file = File.OpenText(path)) {
string line;
while ((line = file.ReadLine()) != null) {
yield return line;
}
}
}
and then use:
var qry = from line in ReadLines(Filename)
select Array.ConvertAll<string,byte>(line.Split('.'), Convert.ToByte);
If you need a list (rather than a sequence);
var list = qry.ToList();
Marc Gravell
2009-12-20 14:15:14