Reputation: 115
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?
Upvotes: 0
Views: 117
Reputation: 22896
The List.ConvertAll
method can be used to convert the list items :
xList = listOfString.ConvertAll(name => new XClass(name));
Upvotes: 0
Reputation: 491
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()
.
Upvotes: 6