Matthew North
Matthew North

Reputation: 555

LINQ select into array

I am trying to modify a LINQ query to select some properties into an array but am struggling to achieve part of it.

    toRun.AddRange(entity.Properties
        .Select(property => property.PrimaryField)
        .Select(field => new { field, entity = entity.EntityName, table = field.Table, key = entity.EntityIdField })

I need this amending so that if a second property called SecondaryField is not null or empty string it will be added to the results of the first Select statement.

For example if entity.Properties contains:

    Property { PrimaryField = "a", SecondaryField = "b" },
    Property { PrimaryField = "c", SecondaryField = "" }

I would like the first Select statement to return:

    { "a", "b", "c" }

Appreciate any help thanks.

Upvotes: 1

Views: 10365

Answers (2)

CodeCaster
CodeCaster

Reputation: 151720

This seems to reproduce what you want: you have a class with two properties:

public class Foo
{
    public string Bar { get; set; }
    public string Baz { get; set; }
}

Of which you have a collection:

var foos = new List<Foo>
{
    new Foo { Bar = "a", Baz = "b" },
    new Foo { Bar = "c", Baz = "" },
};

And from this collection, you want to select all properties that have a non-empty value into an array.

You can do so using SelectMany():

var result = foos.SelectMany(f => new[] { f.Bar, f.Baz })
                 .Where(p => !string.IsNullOrWhiteSpace(p))
                 .ToArray();

You select a new array containing the value of both properties, then filter out the values you don't want, and turn the result into an array again.

Upvotes: 4

Jamiec
Jamiec

Reputation: 136174

This should be pretty simple - get both fields, use a Where to remove the null/empties and turn to an array:

 var result = entity.Properties.SelectMany(p =>new[]{ p.PrimaryField,p.SecondaryField})
            .Where(x => !String.IsNullOrEmpty(x))
            .ToArray();

Live example: http://rextester.com/MHM61977

Upvotes: 1

Related Questions