1

Does anyone know of a shorter (hopefully more elegant) way to initialize a collection of anonymous types in C# than the following:

new[] {
     new[] { "B", "Banana" },
     new[] { "C", "Carrot" },
     new[] { "D", "Durian" },
}.Select(x => new {Value = x[0], Text = x[1] };

2 Answers 2

1

You could use a single array, like this:

Warning: Abominable code ahead!

object temp = null;

new object[] {
    "B", "Banana",
    "C", "Carrot",
    "D", "Durian" 
}.Select((v, i) => i % 2 == 0 ? (temp = v) : new { Value = temp, Text = v })
 .Where((v, i) => i % 2 == 1)
 .ToArray() //Important!

Do not do this, EVER!

Sign up to request clarification or add additional context in comments.

1 Comment

Haha ok, yeah this is gets rid of the repition, and you could hide the Linq calls in a custom extension method... but the code is still terrible like you say.
1

You nearly had it..

var myCollection = new[]
{
    new { Value = "B", Text = "Banana" },
    new { Value = "C", Text = "Carrot" },
    new { Value = "D", Text = "Durian" }
};

3 Comments

That's not shorter. However, it is the best way to do it.
I think this is an equivalant alternative (in terms of readability), but I guess I'm trying to get rid of redundant repetition in the code.
Oh, I see.. I went for more elegant over shorter, missing the question a bit. But stripping out the names of the fields seems like a bit of unnecessary obsfucation to me... imo repetition often isn't bad.

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.