简体   繁体   English

LINQ:如何压缩2个列表并选择第一个列表不同的元素?

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

I have 2 lists/arrays of values, x and y. 我有2个列表/值数组x和y。 There are duplicates in the x list. x列表中有重复项。 I need to select the elements of x and y that have unique x values. 我需要选择具有唯一x值的x和y元素。 Using LINQ, how would I write the query to get the elements of x and y where x is unique? 使用LINQ,我如何编写查询以获取x和y的元素(其中x是唯一的)? (I'd like the first y for every distinct x). (我想要每个不同的x的第一个y)。

Example: 例:

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

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

The result I want is: 我想要的结果是:

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

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

You can get the first x with index, then look up for the index for y. 您可以使用索引获取第一个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();

Zip two lists, group by x , and select the initial item from each group, like this: 压缩两个列表,按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();

If you are willing to add MoreLINQ this can be achieved using DistinctBy : 如果您愿意添加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