Abe
Abe

Reputation: 1929

How to assign values from an object list to another list in c#

I have couple of lists of these classes.

public class Image
{
    public int ImageID { get; set; }
    public int JobAddressID { get; set; }
    public DateTime CreatedDate { get; set; }
    public string Name { get; set; }
    public string Extension { get; set; }
    public string Type { get; set; }
    public Byte[] ImageBytes { get; set; }
    public int Imagetag { get; set; }
}

public class ImageView
{
    public int tag { get; set; }
    public byte[] ImageData { get; set; }
    public DateTime CreatedDate { get; set; }
    public string Name { get; set; }
}

What i would like is assign the values from one list to another without horrible looking foreach loops, something using linq maybe?

My lists are (they are instantiated and ready to go)

 List<Image> _imageList 
 List<ImageView> ImageView

Pseudocode

ImageView.tag = Image.ImageID
 ImageView.ImageData = ImageBytes

I have tried this but still i need another loop to assign the values from blah to my Imageview.

var blah = _imageList.GroupBy(i => new { i.ImageID, i.ImageBytes }).ToArray();

Upvotes: 1

Views: 1490

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

It seems that you would need a Select after the grouping in which you create a new ImageView:

var blah = _imageList.GroupBy(i => new { i.ImageID, i.ImageBytes })
                     .Select(x => new ImageView
                     {
                        tag = x.Key.ImageID,
                        ImageData = x.Key.ImageBytes
                     }).ToList();

disclaimer: I did not take the other 2 properties into account, since you did not specify them in your question.

Attention the grouping by a byte [ ] can lead to unexpected results. Be aware that a comparison will be between the references of the array and not between the content of them. So you will have only the same group if the different object really share the same reference of a single byte [ ] ImageBytes

Upvotes: 1

Related Questions