3

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?

2
  • 2
    Also, note that your struct fields are private right now, they need to be public to use them in the query provided by @EricMagers Commented Oct 24, 2018 at 19:40
  • Do you want to get all of them, or just the first one? And if you want to get all of them, then do you additionally want to get all of their StructInteger arrays combined into one? Commented Oct 24, 2018 at 21:21

2 Answers 2

5
int[] ints = ArrayOfStructs.FirstOrDefault(
                   x => x.StructEnum == ENUMTYPE
             )?.StructIntegers;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. What happens if my ArrayOfStructs doesn't have any elements with the enum I am looking for? Is there a way of checking this out first easily? Otherwise, I can just check if any of its members are default values I suppose.
After this call, if no elements in ArrayOfStructs have the desired enum type, the value of ints will be null. FirstOrDefault() will either return the first match, or null if no value is found. The ? after the Linq query essentially says if this isn't null, then do x. So an element is found, it will go on to assign the StructIntegers property to ints.
2

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

Comments

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.