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

Time:08-18

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 format.

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

Tried as multiple suggessions given in enter image description here

CodePudding user response:

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 });
}
  • Related