简体   繁体   English

c# - 如何将对象列表中的值分配给另一个列表

[英]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?我想要的是将一个列表中的值分配给另一个列表,而没有可怕的 foreach 循环,也许使用 linq 的东西?

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.我已经试过了,但我仍然需要另一个循环来将 blah 中的值分配给我的 Imageview。

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

It seems that you would need a Select after the grouping in which you create a new ImageView :在创建新ImageView的分组之后,您似乎需要一个Select

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.免责声明:我没有考虑其他 2 个属性,因为您没有在问题中指定它们。

Attention the grouping by a byte [ ] can lead to unexpected results.注意按byte [ ]分组可能会导致意外结果。 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因此,如果不同的对象确实共享单个byte [ ] ImageBytes相同引用,那么您将只有相同的组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM