[英]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? 我想有一个简单的方法可以使用LINQ表达式/查询来做到这一点,但是如何根据目标结构内部的特定值从所述结构数组中返回一个结构呢?
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? 如何根据MyStruct[]
的StructEnum
值查找特定元素? Or more specifically, get the StructIntegers
arrays from this specific struct? 更具体地说, StructIntegers
从此特定结构获取StructIntegers
数组?
EDIT: What if ArrayOfStructs
doesn't have any elements that have a specific enum that I am looking for? 编辑:如果ArrayOfStructs
没有包含我要查找的特定枚举的任何元素怎么办? 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
: 这将返回MyEnum
值为a
所有项目:
IEnumerable<MyStruct> structResults = arrayOfStructs.Where(a=>a.StructEnum == MyEnum.a);
This will return all the arrays of StructIntegers
from that result: 这将从该结果返回所有StructIntegers
数组:
IEnumerable<int[]> intArrayResults = structResults.Select(s=>s.StructIntegers);
This will return all the StructIntegers
as a "flat" structure, rather than an IEnumerable
of array: 这会将所有StructIntegers
返回为“平面”结构,而不是数组的IEnumerable
:
IEnumerable<int> intResults = structResults.SelectMany(s=>s.StructIntegers);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.