[英]What is the best way to convert List <string> to List<type> in C#
I'm writing because I did not find a solution to my problem.我写信是因为我没有找到解决我的问题的方法。 I have something like this:
我有这样的事情:
private class MockClass
{
public List<XClass> xList { get; set; }
}
private class XClass
{
public XClass(string name)
{
this.name = name;
}
public string Name{ get; }
}
Next, I have a method which takes a List<string>
, and I want to convert this List<string>
to a list like this:接下来,我有一个接受
List<string>
,我想将此List<string>
转换为这样的List<string>
:
private void CreateRequest(List<string> listOfString)
{
var request = new MockClass
{
xList = // here I have no idea if this can be done
};
}
Is there any point in doing so or just change to string in the MockClass class?这样做有什么意义,或者只是在 MockClass 类中更改为字符串?
Using linq:使用 linq:
xList = listOfString.Select(a => new XClass(a)).ToList();
Edit:编辑:
Use the linq Enumerable.Select
extension method, passing a Func<string, XClass>
selector.使用 linq
Enumerable.Select
扩展方法,传递一个Func<string, XClass>
选择器。 The selector will convert each element of listOfString
from a string
to an instance of XClass
.选择器会将
listOfString
每个元素从string
转换为XClass
的实例。 The result will be an IEnumerable<XClass>
, which you convert to a List<XClass>
by calling ToList()
.结果将是一个
IEnumerable<XClass>
,您可以通过调用ToList()
将其转换为List<XClass>
。
List.ConvertAll
方法可用于转换列表项:
xList = listOfString.ConvertAll(name => new XClass(name));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.