FLICKER
FLICKER

Reputation: 6683

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>

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. Is there a way to do this using LINQ?

Upvotes: 1

Views: 3866

Answers (2)

Ali Bahrami
Ali Bahrami

Reputation: 6073

You can try the code below, it filter the files by the file ext and it's 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

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

Upvotes: 2

Emad
Emad

Reputation: 3929

You can use Directory like this:

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.

Upvotes: 2

Related Questions