[英]Create a new Object for each item in a list
I have below class 我有下课
public class Photo
{
public int ShowOrder { get; set; }
public string Format { get; set; }
public byte[] Image { get; set; }
}
I have hard-coded lines of code to load images from a folder and add them to a variable of type List<Photo>
我有一些硬编码的代码行,可从文件夹加载图像并将其添加到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" }
}
I want to make this part dynamic to it load all photos in the folder, instead of hard-coding. 我想使此部分动态化,以便将所有照片加载到文件夹中,而不是硬编码。
I thought I can use ForEach
function but could not figure out how. 我以为可以使用ForEach
函数,但不知道如何使用。 Is there a way to do this using LINQ
? 有没有办法使用LINQ
做到这一点?
You can use Directory
like this: 您可以像这样使用Directory
:
var Photos = new List<Photo>();
int itt = 1;
foreach(var path in Directory.GetFiles(@"D:\Sample"))
{
Photos.Add(new Photo() {ShowOrder = itt++, Image = File.ReadAllBytes(path)), Format = path.Substring((path.Length - 3), 3) }
}
This works only if all the files in that folder are images but if not you need to tweak the Getfiles()
with a search pattern you can find more here . 仅当该文件夹中的所有文件都是图像时,此方法才有效,如果不是,则需要使用搜索模式对Getfiles()
进行调整,您可以在此处找到更多信息 。
You can try the code below, it filter the files by the file ext and it's 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();
EDIT: 编辑:
I used GetFileExtension instead of SubString 我用的是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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.