将一组对象转换为单行中不同类的另一组对象。 C#

时间:2013-07-05 04:26:02

标签: c#

我有2个类,每个类都有不同的属性。此外,我还有一组A类对象的集合。现在我想将这些对象复制到B类对象的数组中。

这两个类不是相互关联的,每个字段的字段也不同。所以我必须明确地映射我想要复制的字段。现在我正在使用foreach来复制单个元素。 是否有更短的方法来实现这一目标。 这是B级

 public class Event
        {
            public string EventOriginTime { get; set; }
            public string EventReceivedTime { get; set; }
            public int EventCode { get; set; }
            public string CardNumber { get; set; }
            public string ReaderName { get; set; }

        }

头等舱A也会出现类似的情况,但这是第三方派对。

我目前的解决方案是:

List<Event> listOfEvents = new List<Event>();
            foreach (var eachEvent in eventsFromArgus)
            {
                listOfEvents.Add( new Event
                { 
                    ReaderName = eachEvent.DeviceName, 
                    EventCode = eachEvent.EventCode, 
                    EventReceivedTime = eachEvent.ReceiveTime.ToString(), 
                    EventOriginTime = eachEvent.OriginTime.ToString(), 
                    CardNumber = eachEvent.CredentialIdentifier
                });
            }

4 个答案:

答案 0 :(得分:4)

您可以使用LINQ:

List<event> listOfEvents = 
    (from eachEvent in eventsFromArgus
     select new Event(
         ReaderName = eachEvent.DeviceName, 
         EventCode = eachEvent.EventCode, 
         EventReceivedTime = eachEvent.ReceiveTime.ToString(), 
         EventOriginTime = eachEvent.OriginTime.ToString(), 
         CardNumber = eachEvent.CredentialIdentifier)).ToList();

但这与你已经拥有的并没有太大的不同。

或者,您可以查看类似AutoMapper的内容。

答案 1 :(得分:3)

另一种方法是将第三方对象直接传递给Event类的构造函数:

public class Event
{
    private readonly ThirdPartyClass _eventFromArgus;

    public Event(ThirdPartyClass eventFromArgus)
    {
        _eventFromArgus = eventFromArgus;
    }

    public string ReaderName { get { return _eventFromArgus.DeviceName; } }
    // etc.
}

然后你可以这样做:

var listOfEvents = eventsFromArgus.Select(eachEvent => new Event(eachEvent));

答案 2 :(得分:2)

与Jim建议的linq一样,但有点不同

var listOfEvents = eventsFromArgus.Select(eachEvent => 
    new Event( ReaderName = eachEvent.DeviceName, 
               EventCode = eachEvent.EventCode, 
               EventReceivedTime = eachEvent.ReceiveTime.ToString(), 
               EventOriginTime = eachEvent.OriginTime.ToString(), 
               CardNumber = eachEvent.CredentialIdentifier)).ToList();

答案 3 :(得分:1)

您可以向Event类添加构造函数:

public Event(string EventOriginTime, string EventReceivedTime, int EventCode, string CardNumber, string ReaderName)
{
    this.EventOriginTime = EventOriginTime;
    this.EventReceivedTime = EventReceivedTime;
    this.EventCode = EventCode;
    this.CardNumber = CardNumber;
    this.ReaderName = ReaderName;
}

然后,至少在创建新实例时不必指定字段名称。

List<Event> listOfEvents = new List<Event>();
foreach (var eachEvent in eventsFromArgus)
{
    listOfEvents.Add(new Event(eachEvent.OriginTime.ToString(), eachEvent.ReceiveTime.ToString(), eachEvent.EventCode, eachEvent.DeviceName)
}