tags:

views:

131

answers:

2
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();
    });
+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
`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
Thanks for the correction, Kobi. I've changed the answer.
Marcelo Cantos
thanks. much appreciated.
adge
+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