[英]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.寻找将
List<string>
的所有元素转换/转换为具有一个字符串属性的特定类型列表的直接方法。
Type Class with one string property:类型 Class 具有一个字符串属性:
public class ClaimNumber
{
public string claimNumber { get; set; }
}
The List I receive from webservice is in List<string>
format.我从 webservice 收到的列表是
List<string>
格式。
I need to convert/cast List<string> to List<ClaimNumber>
我需要将
List<string> to List<ClaimNumber>
Tried as multiple suggessions given in Shorter syntax for casting from a List<X> to a List<Y>?尝试作为从 List<X> 转换为 List<Y> 的更短语法中给出的多个建议? , but those did not work in above case.
,但这些在上述情况下不起作用。 Please suggest the right way to achieve this.
请提出正确的方法来实现这一目标。
Simply run through each element and create a new ClaimNumber
object, populating the property.只需遍历每个元素并创建一个新的
ClaimNumber
object,填充属性。
With Linq:使用 Linq:
// List<string> source = ...
List<ClaimNumber> claims = source.Select(s => new ClaimNumber { claimNumber = s }).ToList();
With a foreach有一个 foreach
// List<string> source = ...
List<ClaimNumber> claims = new();
foreach (var s in source)
{
claims.Add(new ClaimNumber { claimNumber = s });
}
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:这将返回:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.