0

I have a LINQ query that selects a list of teamIDs and team names to populate a drop down list. The query looks like this:

var teams = db.Teams.Where(t => t.isActive)
                    .Select(t => new {t.TeamID, t.TeamName});

However, I want the result set to be in the form of a 2D string array, since that's what my function that populates DDLs requires. I know I can use a for loop and build the array, but I'd prefer it, if possible to do it all in one step.

Is there something similar to this?

string[][] teams = db.Teams.Where(t => t.isActive)
                           .Select(t => new {t.TeamID, t.TeamName})
                           .To2DArray();

2 Answers 2

4

Note that string[][] is not a multi-dimensional array, it's an array of arrays. Multidimensional arrays look like string[,], and have different semantics (i.e. an array of arrays may have subarrays of differing lengths, but all rows/columns in a multidimensional array have the same length).

Since you're just dealing with arrays of arrays, the easiest solution is probably using ToArray on a sequence of items which are themselves created with ToArray.

The following code assumes that db.Teams is also an array of arrays:

var teams =
    db.Teams
    .Select(teamArray =>
        teamArray
        .Where(t => t.isActive)
        .Select(t => new {t.TeamID, t.TeamName})
        .ToArray())
    .ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Off topic and I know you already know this, true "multidimensional" arrays (string[,]) in .NET are an abomination: slower to access, hard as hell to write generic methods to operate on (for an arbitrary # of dimensions at least), and under all sorts of one-off-ish arcane rules.
3

Kind of:

string[][] teams = db.Teams.Where(t => t.isActive).Select(t => new[] {t.TeamID, t.TeamName}).ToArray();

3 Comments

You confused the anonymous object syntax, new { a,b,c=c } with the array initializer syntax new[] {a,b,c}.
Other direction. The question is making an anonymous type, but I think you read it as making an array.
@Strilanc Oh, that's my fix!

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.