简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM