将数据添加到列表而不替换旧值 [英] Add data to a list with out replacing the old value

查看:71
本文介绍了将数据添加到列表而不替换旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表'objlistCropped',当我尝试使用foreach循环向该列表添加值时,所有列表值都被最后一个值替换。

I have a list 'objlistCropped' and when i tried to add values to this list using a foreach loop all the list value is replaced by last value.

string strCroppedImagePaths = @"C:\CropImages";
            Selected objCropped = new Selected();
            Source objSource = new Source();
            ArrayList listCropped = new ArrayList();
            DirectoryInfo d = new DirectoryInfo(strCroppedImagePaths);

         FileInfo[] file = d.GetFiles("*.Jpeg").OrderBy(fi => int.Parse(Path.GetFileNameWithoutExtension(fi.Name).TrimStart("Image".ToArray()))).ToArray();
            DataTable dt = new DataTable();
            int RowID = 0;

            foreach (FileInfo file2 in file)
            {
                if (file2.Extension == ".jpg" || file2.Extension == ".Jpeg" || file2.Extension == ".gif" || file2.Extension == ".png" || file2.Extension == ".bmp")
                {
                    //listCropped.Add(file2);
                    string strCroppedImagename = file2.Name;
                   
                    RowID++;
                    
                    objCropped.Image = strCroppedImagename;
                    objlistCropped.Add(objCropped);
                }
            }





如果文件夹有10张图片,所有列表值都是最后一张图片(Image10)。



if folder having 10 images, all the list values are last image (Image10).

推荐答案

你肯定想写这个(只是输入错误):



You wanted to write this one surely (just a typing error):

//listCropped.Add(file2);
 foreach (FileInfo file2 in file)
 {
      if (file2.Extension == ".jpg" || file2.Extension == ".Jpeg" || file2.Extension == ".gif" || file2.Extension == ".png" || file2.Extension == ".bmp")
            //string strCroppedImagename = file2.Name;
            string strCroppedImagename = file.Name;


您的代码确实不显示'objlistCropped的定义位置,但是,假设它是类型列表'已选择:



1.发生错误是因为您正在重新使用相同的实例选择,'objCropped,每次:'objCropped显然是参考类型。



2.你可以解决这个问题,我很确定,只需创建一个每次更新列表时选择添加的新实例:
Your code does not show where 'objlistCropped is defined, but, assuming it is a List of Type 'Selected:

1. The error occurs because you are re-using the same instance of a Selected, 'objCropped, each time: 'objCropped is clearly a reference Type.

2. You can fix this, I am pretty sure, by just creating a new Instance of 'Selected to add each time you update the List:
objCropped = new Selected();
objCropped.Image = strCroppedImagename;
objlistCropped.Add(objCropped);

当然,如果你使用这种方法,那么你可以在代码的开头声明'objcropped而不初始化它。

Of course, if you used this approach, then you could declare 'objcropped at the start of your code without initializing it.


这篇关于将数据添加到列表而不替换旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆