簡體   English   中英

LINQ:如何壓縮2個列表並選擇第一個列表不同的元素?

[英]LINQ: how to zip 2 lists and select elements where first list is distinct?

我有2個列表/值數組x和y。 x列表中有重復項。 我需要選擇具有唯一x值的x和y元素。 使用LINQ,我如何編寫查詢以獲取x和y的元素(其中x是唯一的)? (我想要每個不同的x的第一個y)。

例:

x = {1, 1, 2, 3, 4, 4, 5, 6}

y = {3, 4, 5, 6, 7, 8, 9, 10}

我想要的結果是:

newX = {1, 2, 3, 4, 5, 6}

newY = {3, 5, 6, 7, 9, 10}

您可以使用索引獲取第一個x,然后查找y的索引。

var xWithIndex = x.Select((value, index) => new { Value = value, Index = index })
         .GroupBy(item => item.Value)
         .Select(group => group.First())
var newX = xWithIndex.Select(item => item.Value).ToList();
var newY = xWithIndex.Select(item => y[item.Index]).ToList();

壓縮兩個列表,按x分組,然后從每個組中選擇初始項,如下所示:

var pairs = x.Zip(y, (first, second) => new {X = first, Y = second})
    .GroupBy(i => i.X)
    .Select(g => g.First());
var newX = pairs.Select(p => p.X).ToList();
var newY = pairs.Select(p => p.Y).ToList();

如果您願意添加MoreLINQ,可以使用DistinctBy實現:

int[] x = { 1, 1, 2, 3, 4, 4, 5, 6 };
int[] y = { 3, 4, 5, 6, 7, 8, 9, 10 };

var result = x.Zip(y, (a,b) => new { x = a, y = b})
    .DistinctBy(z => z.x).ToList();

var xresult = result.Select(z => z.x);
var yresult = result.Select(z => z.y);

// Verify the results
Console.WriteLine(String.Join(",", xresult));
Console.WriteLine(String.Join(",", yresult));

暫無
暫無

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

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