我有下课
public class Photo
{
public int ShowOrder { get; set; }
public string Format { get; set; }
public byte[] Image { get; set; }
}
我有一些硬编码的代码行,可从文件夹加载图像并将其添加到类型为变量的变量中 List<Photo>
var Photos = new List<Photo>()
{
new Photo() { ShowOrder = 1, Image = File.ReadAllBytes("D:\\Sample\\pic1.jpg")), Format = "jpg" },
new Photo() { ShowOrder = 2, Image = File.ReadAllBytes("D:\\Sample\\pic2.png")), Format = "png" },
new Photo() { ShowOrder = 3, Image = File.ReadAllBytes("D:\\Sample\\pic3.jpg")), Format = "jpg" },
new Photo() { ShowOrder = 4, Image = File.ReadAllBytes("D:\\Sample\\pic4.gif")), Format = "gif" }
}
我想使该部分动态化,以便将所有照片加载到文件夹中,而不是硬编码。
我以为我可以使用ForEach
功能,但不知道如何使用。有没有办法做到这一点LINQ
?
您可以尝试下面的代码,它通过ext文件过滤文件,它是LINQ
;
// directory path which you are going to list the image files
var sourceDir = "directory path";
// temp variable for counting file order
int fileOrder = 0;
// list of allowed file extentions which the code should find
var allowedExtensions = new[] {
".jpg",
".png",
".gif",
".bmp",
".jpeg"
};
// find all allowed extention files and append them into a list of Photo class
var photos = Directory.GetFiles(sourceDir)
.Where(file => allowedExtensions.Any(file.ToLower().EndsWith))
.Select(imageFile => new Photo()
{
ShowOrder = ++fileOrder,
Format = imageFile.Substring(imageFile.LastIndexOf(".")),
Image = File.ReadAllBytes(imageFile)
})
.ToList();
编辑:
我用的是GetFileExtension而不是SubString
Directory.GetFiles(sourceDir))
.Where(file => allowedExtensions.Any(file.ToLower().EndsWith))
.Select(imageFile => new Photo()
{
ShowOrder = ++fileOrder,
Image = File.ReadAllBytes(imageFile),
Format = Path.GetExtension(imageFile)
}
).ToList()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句