LINQ:如何在select期间转换查询结果?

时间:2011-01-04 21:48:22

标签: c# linq .net-3.5 type-conversion

这将返回strings

的列表
var filesizes = from fd in files
                from tag in fd.Tags
                where tag.Id == ID.FILESIZE
                select tag.Value;

以下内容不起作用,但在查询过程中是否可以采用类似方法将string转换为int

var filesizes = from fd in files
                from tag in fd.Tags
                where tag.Id == ID.FILESIZE
                select new { int.Parse(tag.Value) };

或者我应该使用ConvertAll as suggested here

3 个答案:

答案 0 :(得分:5)

你可以这样做:

var filesizes = from fd in files
                from tag in fd.Tags
                where tag.Id == ID.FILESIZE
                select new { FileSize = int.Parse(tag.Value) };

var filesizes = from fd in files
                from tag in fd.Tags
                where tag.Id == ID.FILESIZE
                select int.Parse(tag.Value);

答案 1 :(得分:1)

您可以将select int.Parse(tag)放在最后而不是select tag.Value

var filesizes = from fd in files
                from tag in fd.Tags
                where tag.Id == ID.FILESIZE
                select int.Parse(tag.Value);

答案 2 :(得分:0)

为什么需要用新的{...}包装整数?这很简单:

var filesizes = from fd in files
                from tag in fd.Tags
                where tag.Id == ID.FILESIZE
                select int.Parse(tag.Value);