使用 Linq 创建一个 KeyValuePair<byte, string[]>

Create a KeyValuePair<byte, string[]> with Linq

我正在使用 .NET Framework 4.6.2、Entity Framework 6.1.3 和存储库模式开发 C# 库。

我想在 select 中创建一个 KeyValuePair<byte, string[]>,如下所示:

Dictionary<string, byte> dict = 
    GetAggregationLevelsNameId(arvatoConnectionString, productionOrderId);

KeyValuePair<byte, string[]>[] codes = null;

List<Data.Code> aCodes =
    repo.SearchFor(c => c.ProductionOrderId == productionOrderId).ToList();

if ((aCodes != null) && (aCodes.Count > 0))
{
    codes =
        aCodes
            .Select(ac => new { ac.Level, ac.Serial })
            .AsEnumerable()
            .Select(ac => new KeyValuePair<byte, string[]>(dict[ac.Level], ac.Serial))
            .ToArray();
}

但是这里.Select(ac => new KeyValuePair<byte, string[]>(dict[ac.Level], ac.Serial))我得到以下错误:

Cannot convert string to string[].

如何在 select 中创建 KeyValuePair<byte, string[]>

我想将具有相同ac.Level的所有ac.Serial组合成一个KeyValuePair

ac 是一个我没有在任何地方声明的结构。我在这里创建它 Select(ac => new { ac.Level, ac.Serial }).

ac.Level 是一个 string
ac.Serial 是一个 string.

更新:
我有这段代码可以将 select 转换为 Dictionary(请注意,以下字典的键为 string,而不是我想要的 byte现在创建):

GenericRepository<Data.Code> repo =
    new GenericRepository<Data.Code>(context);

codes =
    repo
        .SearchFor(c => c.ProductionOrderId == productionOrderId)
        .GroupBy(c => c.Level)
        .ToDictionary(dic => dic.Key, dic => dic.Select(c => c.Serial).ToList());

更新 2:
Data.Code 是一个 POCO 对象,表示数据库 table,其中有很多 Serial 具有相同的 Level

试试这个

codes =
    aCodes
        .AsEnumerable()
        .GroupBy(ac => dict[ac.Level])
        .Select(ac => new KeyValuePair<byte, string[]>(ac.Key, ac.Select(a => a.Serial).ToArray()))
        .ToArray();

或字典:

codes =
    aCodes
        .AsEnumerable()
        .GroupBy(ac => dict[ac.Level])
        .ToDictionary(ac => ac.Key, ac.ToArray());