开发者

Can I do this better using LINQ

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)
        {
            re开发者_开发问答turn Convert.ToByte(byteVal);
        }).ToArray();
    });


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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜