6

If I have a simple class that looks like this:

public string Param1 { get; set; }
public string Param2 { get; set; }
public SimpleClass (string a, string b) { Param1 = a; Param2 = b; }

List of string array returned from another class:

var list = new List<string[]> {new[] {"first", "second"}, new[] {"third", "fourth"}};

Is there a more efficient way using C# to end up with List<SimpleClass> without doing something like:

var list1 = new List<SimpleClass>();
foreach (var i in list)
{          
    var data = new SimpleClass(i[0], i[1]);
    list1.Add(data);         
}
1
  • Could mean, not creating redundant variables inside foreach, or perhaps a standard library that does such things. Commented Oct 18, 2016 at 22:17

2 Answers 2

10

You can use Linq:

var simpleClassList = originalList.Select(x => new SimpleClass(x[0], x[1])).ToList()
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, or with the very old-fashioned ConvertAll instance method var simpleClassList = originalList.ConvertAll(x => new SimpleClass(x[0], x[1])); where a List<> is returned directly (so no lazy enumerator).
3

As was said by @rualmar you can use linq. But you also can overload implicit operator. For example

public static implicit operator SimpleClass(string[] arr)
{
    return new SimpleClass(arr[0], arr[1]);
}

and after that you can write this

var list = new List<SimpleClass> { new[] { "first", "second" }, new[] { "third", "fourth" } };

1 Comment

Thanks for this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.