簡體   English   中英

C#根據特定的struct成員值從數組中獲取struct

[英]C# get struct from array based on specific struct member value

我想有一個簡單的方法可以使用LINQ表達式/查詢來做到這一點,但是如何根據目標結構內部的特定值從所述結構數組中返回一個結構呢?

例如,假設我們有:

enum MyEnum
{
    a,
    b,
    c
}

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

MyStruct[] ArrayOfStructs;

如何根據MyStruct[]StructEnum值查找特定元素? 更具體地說, StructIntegers從此特定結構獲取StructIntegers數組?

編輯:如果ArrayOfStructs沒有包含我要查找的特定枚舉的任何元素怎么辦? 首先檢查出來的聰明方法是什么?

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

這將返回MyEnum值為a所有項目:

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

這將從該結果返回所有StructIntegers數組:

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

這會將所有StructIntegers返回為“平面”結構,而不是數組的IEnumerable

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM