[英]How to create dictionary<int, string> from IEnumearble<IEnumerable<int, string>>
在這里有一個復雜的 Linq 表達式。 目前我只能創建 IEnumearble,但我需要解析為 IEnumerable<int, string>。 我不知道如何獲取該“字符串”。
IEnumerable<IEnumerable<int>> uniqueColumns = test
.Where(e => e.ToolParameters != null)
.Select(x => x.ToolParameters.Select(u => u.ToolParameterTypeId))
.Distinct();
uniqueColumnIds = uniqueColumns
.SelectMany(a => a)
.Distinct();
如您所見,我檢查“ToolParameters”是否為 null。如果不是,則我為 select“ToolParametersTypeId”,但我還需要 select“ToolParameteresTypeName”,但不知道如何...
之后,我需要將 Ienumearble<Ienumearble<>> 解析為僅一個 Ienumerable,因為我的目標是從一堆列表中獲取唯一值。 但是我需要制作一個字典,其中包含來自一堆列表的唯一鍵,字符串值......
我有 uniqueColumnIds,但我還需要獲取 uniqueColumnNames 並將它們放在一起以獲得鍵值對的字典。 也許有人對如何做到這一點有任何想法?
字典不是正確的結構,因為每個鍵只能出現一次。 如果ToolParametersTypeId
具有多個對應的ToolParameteresTypeName
,那么您將需要丟棄除一個ToolParameteresTypeName
的所有。 更合適的結構可能是IEnumerable<(int, string)>
:
IEnumerable<(int ToolParameterTypeId, string ToolParameteresTypeName)> uniqueColumns =
test
.Where(e => e.ToolParameters != null)
.SelectMany(e => e.ToolParameters.Select(tp =>
(tp.ToolParameterTypeId, tp.ToolParameteresTypeName)))
.Distinct();
SelectMany
將嵌套的IEnumerable
展平,嵌套的Select
將每個項目投影到一個ValueTuple
中。
在IEnumerable<ValueTuple>
上使用Distinct
然后根據每個元組組件的值檢查是否相等,而不是通過引用,因此您將以不同的ToolParameterTypeId
和ToolParameteresTypeName
對結束。
這很容易。
IEnumerable<IEnumerable<(int key, string value)>> target = default; // replace default.
var dict = target.SelectMany(x => x).ToDictionary(x => x.key, x => x.value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.