亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

過濾二維數組的技巧

過濾二維數組的技巧

C#
慕雪6442864 2023-09-09 16:33:11
下面是一個 JSON 示例: item: {   id: 1,   variants: [    {     id: 1,     prices: [      {       needle: 100      },      {       needle: 200      }     ]    }   ] }基本上我希望能夠選擇價格范圍內的所有針值。有人能把我推向正確的方向嗎?如果價格維度不存在,我將能夠執行以下操作:item.variants.Select(v => v.needle.ToString()))我嘗試過什么...item.variants.Where(x => x.prices != null)               .SelectMany(v =>                  v.prices.Select(p =>                    p.needle.ToString()                 ).Distinct()               )結果應該是[0] [string] "100", [1] [string] "200"
查看完整描述

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。


查看完整回答
反對 回復 2023-09-09
?
米脂

TA貢獻1836條經驗 獲得超3個贊

像這樣的事情怎么樣:

items.variants
    .Where(v => v.Prices != null)
    .SelectMany(v => v.prices)
    .Select(p => p.needle.ToString())
    .Distinct();

SelectMany將數組展平prices為單個IEnumerable<Price>.

Selectneedle值投影到IEnumerable<string>.

Distinct只得到不同的needle值。


查看完整回答
反對 回復 2023-09-09
?
茅侃侃

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));


查看完整回答
反對 回復 2023-09-09
  • 3 回答
  • 0 關注
  • 175 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號