2016-12-04 6 views
0

У меня есть ниже классаСоздать новый объект для каждого элемента в списке

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?

ответ

1

Вы можете использовать этот код ниже, он фильтрует файлы по файлу 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:

Я использовал GetFileExtension вместо подстроки

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

Именно то, что я искал. Однако я могу использовать GetFileExtension вместо Substrting. Спасибо. Я обновляю ответ. – FLICKER

2

Вы можете использовать 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) } 
} 

Это работает только если все файлы в этой папке находятся изображения, но если вам не нужно настроить Getfiles() с шаблоном поиска вы можете найти больше here.

+1

Я думаю, вы должны двигаться 'Int ITT = 1' к внешней стороне' foreach' цикла. –

+0

@RichardSchneider Да, спасибо. – Emad

+1

Вы можете использовать Path.GetExtension() для получения формата, который также будет работать со всеми типами файлов длины и не только с тремя буквами. (например jpeg) – PartlyCloudy

Смежные вопросы