Shane Berezowski
Shane Berezowski

Reputation: 33

C# get struct from array based on specific struct member value

I imagine there is an easy way to do this with LINQ expressions / queries, but how would one return a struct from an array of said structs, based on a specific value found inside of target struct?

For example, let's say we had:

enum MyEnum
{
    a,
    b,
    c
}

struct MyStruct
{
    MyEnum StructEnum;
    int[] StructIntegers;
}

MyStruct[] ArrayOfStructs;

How would I find from MyStruct[] a specific element based on its StructEnum value? Or more specifically, get the StructIntegers arrays from this specific struct?

EDIT: What if ArrayOfStructs doesn't have any elements that have a specific enum that I am looking for? What is a smart way of checking this out first?

Upvotes: 3

Views: 1143

Answers (2)

emagers
emagers

Reputation: 911

int[] ints = ArrayOfStructs.FirstOrDefault(
                   x => x.StructEnum == ENUMTYPE
             )?.StructIntegers;

Upvotes: 5

MikeH
MikeH

Reputation: 4395

This will return all of the items that have MyEnum value of a:

IEnumerable<MyStruct> structResults = arrayOfStructs.Where(a=>a.StructEnum == MyEnum.a);

This will return all the arrays of StructIntegers from that result:

IEnumerable<int[]> intArrayResults = structResults.Select(s=>s.StructIntegers);

This will return all the StructIntegers as a "flat" structure, rather than an IEnumerable of array:

IEnumerable<int> intResults = structResults.SelectMany(s=>s.StructIntegers);

Upvotes: 2

Related Questions