3 回答

TA貢獻1777條經驗 獲得超10個贊
這應該可以解決問題:
var result = structure.variants
// Throw away variants without prices
.Where(variant => variant.prices != null)
// For each variant, select all needle prices (.toString) and flatten it into 1D array
.SelectMany(variant => variant.prices.Select(price => price.needle.ToString()))
// And choose only unique prices
.Distinct();
對于這樣的結構:
var structure = new Item(
new Variant(new Price(200), new Price(100), new Price(800)),
new Variant(new Price(100), new Price(800), new Price(12))
);
是輸出[ 200, 100, 800, 12 ]。
它是如何工作的?
.SelectMany基本上采用 array-inside-array 并將其轉換為普通數組。[ [1, 2], [3, 4] ] => [ 1, 2, 3, 4 ],并.Distinct丟棄重復的值。
我想出的代碼幾乎和你的一模一樣??雌饋砟阏谧?Distincton .Select,而不是 on .SelectMany。有什么不同?.Select選擇一個值(在本例中) - 對它調用 Distinct 是沒有意義的,這會刪除重復項。.SelectMany選擇許多值 - 所以如果你想在某個地方調用 Distinct,它應該在 的結果上SelectMany。

TA貢獻1836條經驗 獲得超3個贊
像這樣的事情怎么樣:
items.variants .Where(v => v.Prices != null) .SelectMany(v => v.prices) .Select(p => p.needle.ToString()) .Distinct();
SelectMany
將數組展平prices
為單個IEnumerable<Price>
.
Select
將needle
值投影到IEnumerable<string>
.
Distinct
只得到不同的needle
值。

TA貢獻1842條經驗 獲得超21個贊
朝著正確方向的一個小推動可能是您在 select Many 中選擇超過 1 個元素,并使用 select 的迭代器參數來稍后獲取項目索引。例如:
var result = item.variants
.Where(x => x.prices != null)
.SelectMany(o => o.prices.Select(x => new {Type = x.needle.GetType(), Value = x.needle}))
.Select((o, i) => $"[{i}] [{o.Type}] {o.Value}").ToList();
Console.WriteLine(string.Join(",\n", result));
- 3 回答
- 0 關注
- 175 瀏覽
添加回答
舉報