Pinu
Pinu

Reputation: 7510

WCF Web Service - List<> Return type

List<CertMail> lsRecipetNumber = new List<CertMail>();

CertMail class is in data access layer which returns a List<CertMail>. I need to convert this to the object of my class and return that

List<CertMailReceiptNumbers> lsReceiptNumbers = new List<CertMailReceiptNumbers>();


CertMailReceipt.lsCMRN = lsReceiptNumbers; //---- > return this.

How do i add all the rows in the CertMail list to CertMailRecieptNumbers and return that from CertMailRecieptNumbers class?

Upvotes: 0

Views: 1440

Answers (2)

marc_s
marc_s

Reputation: 754258

If you only need to map from CertMail to CertMailReceipt and the two types are very similar, you could use an automagic helper like AutoMapper to help you with the mapping.

Basically, AutoMapper will handle much of the boring and error-prone left-right code - assigning one property on the target to a property on the source object.

In your case, if the two types are somewhat similar, you could do something like:

using AutoMapper;

Mapper.CreateMap<CertMail, CertMailReceipt>();

sourceList.ForEach(certMail => 
{
    lsReceiptNumbers.Add(Mapper.Map<CertMail, CertMailReceipt>(certMail))
});

or if you prefer:

using AutoMapper;

Mapper.CreateMap<CertMail, CertMailReceipt>();

foreach(certMail cm in sourceList)    
{
    lsReceiptNumbers.Add(Mapper.Map<CertMail, CertMailReceipt>(cm));
}

This is basically the same idea that NPayette mentioned, just using an half-automatic mapper, instead of having to write the whole mapping process yourself.

And with a bit of luck (and depending on your types of data structures), you might even get the benefit of Automapper being able to even map entire lists from one type to another:

lsReceiptNumbers = Mapper.Map<List<CertMail>,
                              List<CertMailReceipt>>(sourceList);

Automapper will go through the list of items itself, and apply its mapping to each item, and add those to the resulting output list.

Upvotes: 2

NPayette
NPayette

Reputation: 179

If I understand correctly your need it's a simple mather of mapping from one to another.

Well you need to go throu your CertMail list and then for each of them create a new CertMailReceiptNumbers

Ex.

...
lsReceiptNumber.ForEach(certMail => 
{
    lsReceiptNumbers.Add(convertToCertMailReceiptNumber(certMail));
});

return lsReceiptNumber
}

Public CertMailReceiptNumbers convertToCertMailReceiptNumber(CertMail cm) 
{
     var cmrn = new ertMailReceiptNumber();
     cmrn.xxx = cm.xxxx;
     ...;
     return cmrn;
}

Upvotes: 0

Related Questions