Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting or casting List<sting> to List<type> in c#

Looking for direct way to convert/cast all elements of List<string> to a list of particular type which has one string property.

Type Class with one string property:

 public class ClaimNumber
    {
        public string claimNumber { get; set; }
    }

The List I receive from webservice is in List<string> format.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need to convert/cast List<string> to List<ClaimNumber>

Tried as multiple suggessions given in Shorter syntax for casting from a List<X> to a List<Y>?, but those did not work in above case. Please suggest the right way to achieve this.

>Solution :

Simply run through each element and create a new ClaimNumber object, populating the property.

With Linq:

// List<string> source = ...
List<ClaimNumber> claims = source.Select(s => new ClaimNumber { claimNumber = s }).ToList();

With a foreach

// List<string> source = ...
List<ClaimNumber> claims = new();
foreach (var s in source)
{
    claims.Add(new ClaimNumber { claimNumber = s });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading