Matthew North Matthew North - 1 year ago 209
C# Question

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.

.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.

Answer Source

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))

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download