我们如何筛选两个列表 [英] How we filter two lists

查看:76
本文介绍了我们如何筛选两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

填写下面的C#方法,返回list1或list2中的数字列表,但不是两个列表。

Fill out the C# method below to return a list of numbers that are in either list1 or list2, but not both lists.

public List<int> ListDifference(List<int> list1, List<int> list2)
{
  // FILL ME OUT
}

推荐答案

使用Linq有一个非常简单的方法。基本上,您将列表连接在一起并对它们进行分组,然后搜索其计数为1的项目。尝试查询大小:
There''s a really simple way to do this with Linq. Basically, you concatenate the lists together and group them, then you search for items where the count of them is 1. Try this query out for size:
List<int> countDistinct = firstList.Concat(secondList)
  .GroupBy(x => x)
  .Where(g => g.Count() == 1)
  .Select(g => g.Key).ToList();

它就像那样简单 - 并且读取比尝试比较两个独立循环更容易阅读。



我对此解决方案与解决方案3提供的解决方案进行了比较,时间差异非常惊人。我创建了两个列表,第一个包含100万个数字,第二个包含200万个数字 - 在2个列表中只有6个数字不匹配。 Contains解决方案在大型集合上是一种非常低效的搜索机制,因此搜索最终需要花费大量时间。说实话,我放弃了大约20分钟后等待第二次搜索返回。 Linq解决方案耗时1745毫秒。

It''s as easy as that - and reads a lot easier to read than trying to compare two independent loops.

I did a comparison between this solution and the solution presented as Solution 3, and the time difference was quite staggering. I created two lists, the first had 1 million numbers in it, and the second had 2 million numbers - only 6 numbers don''t match between the 2 lists. The Contains solution is a very inefficient search mechanism on large sets, so the search ends up taking an inordinate amount of time. To be honest, I gave up waiting for the second search to return after about 20 minutes. The Linq solution took 1745 milliseconds.


您好,



试试这个:

Hi,

Try this:
public List<int> ListDifference(List<int> list1, List<int> list2)
{
  list1.Except(list2).Concat(list2.Except(list1)).ToList();





Enumerable.Except(TSource) [ ^ ]



希望这会有所帮助。



Enumerable.Except(TSource)[^]

Hope this helps.


试试此代码以获得差异



try this code to get difference

for(int i=0;i<list1.Count;i++)
          {
              if(!list2.Contains(list1[i]))
                  c.Add(list1[i]);
          }

           for(int i=0;i<list2.Count;i++)
          {
              if(!list1.Contains(list2[i]) && !c.Contains(list2[i]))
                  c.Add(list1[i]);
          }
return c;


这篇关于我们如何筛选两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆