简体   繁体   中英

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:

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?

Using linq:

xList = listOfString.Select(a => new XClass(a)).ToList();

Edit:

Use the linq Enumerable.Select extension method, passing a Func<string, XClass> selector. The selector will convert each element of listOfString from a string to an instance of XClass . The result will be an IEnumerable<XClass> , which you convert to a List<XClass> by calling ToList() .

List.ConvertAll方法可用于转换列表项:

xList = listOfString.ConvertAll(name => new XClass(name));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM