简体   繁体   English

转换列表的最佳方法是什么<string>列出<type>在 C# 中

[英]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.

相关问题 在字符串列表C#中搜索字符串的最佳方法是什么 - What is the best way to search for a string in a list of list of strings c# 在C#中,转换List的最佳方法是什么 <T> 到SortedDictionary <string, T> ? - In C#, what is the best way to convert a List<T> to a SortedDictionary<string, T>? 在 C# 中有没有办法将链表转换为字符串? - In C# is there a way to convert a linked list to a string? 在C#中,查看列表是否包含其他列表的最佳方法是什么? - In C#, What is the best way to see if a list contains another list? 将返回字符分隔的字符串转换为List <string>的最佳方法是什么? - What is the best way to convert a string separated by return chars into a List<string>? 将字典转换为自定义 KeyValuePair 类型列表的最佳方法是什么? - What is the best way to convert dictionary to a custom KeyValuePair type list? 转换VB if语句将字符串返回到C#的最佳方法是什么 - What is the best way to convert VB if statement that return a string to C# 在Unity(C#)中将UI文本转换为字符串的最佳方法是什么? - What is the best way to convert a UI text to string in Unity (C#)? 转换列表的最佳方法<Tuple<double, double> &gt; 到 [,] 数组在 C# - Best way to convert a List<Tuple<double, double>> to [,] array in C# 在C#中,按字符串属性对对象列表进行排序并获得正确顺序的最佳方法是什么? - In C#, what is the best way to sort a list of objects by a string property and get correct order?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM