skip to Main Content

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.

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.

2

Answers


  1. Here is how you can do this:

    void Main()
    {
        List<string> c1List = new List<string>();
        List<ClaimNumber> c2List = new List<ClaimNumber>();
    
        c1List.Add("1234");
        c1List.Add("4321");
        c1List.Add("1111");
        c1List.Add("9999");
    
        c2List.AddRange(c1List.Select(x => new ClaimNumber
        {
            claimNumber = x
        }));
        
    }
    
    public class ClaimNumber
    {
        public string claimNumber { get; set; }
    }
    

    This returns:

    enter image description here

    Login or Signup to reply.
  2. 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 });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search