c# 两个list的交集问题!

caoyuanlangzi001 2010-08-08 01:34:30
我写了个方法。

public void newList (List<object> a,List<object> b)
{

List<object> c= new List<object>();

for (int i = 0; i < a.Count; i++)
{
if(a[i].Equals(b[i]))
{
c.Add(a[i]);
}
}


我不知道是否有别的高效率的方法可以解决此问题,知道的分享下,谢谢!
...全文
415 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
caoyuanlangzi001 2010-08-08
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 peter200694013 的回复:]
引用 3 楼 caoyuanlangzi001 的回复:
那如何做到相对完善些呢?

如果照你的那么判断,就要2层循环

public void newList (List<object> a,List<object> b)
{

List<object> c= new List<object>();

for (int i = 0; i < a.Count; i+……
[/Quote]

如何List<object> a小于List<object> b呢?
Peter200694013 2010-08-08
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 caoyuanlangzi001 的回复:]
那如何做到相对完善些呢?
[/Quote]
如果照你的那么判断,就要2层循环

public void newList (List<object> a,List<object> b)
{

List<object> c= new List<object>();

for (int i = 0; i < a.Count; i++)
{
for(int j = 0; j < b.Count;j++)
{
if(a[i].Equals(b[j]) && !c.Contains(a[i]))
{
c.Add(a[i]);
}
}
}
wuyq11 2010-08-08
  • 打赏
  • 举报
回复
LINQ Intersect
List<string> lst1 = new List<string>(){"A"};
List<string> lst2= new List<string>() { "B"}
vae result= lst1.Intersect(lst2, StringComparer.OrdinalIgnoreCase);
Peter200694013 2010-08-08
  • 打赏
  • 举报
回复

List<Int32> list1 = new List<Int32>();
List<Int32> list2 = new List<Int32>();

list1.Add(1);
list1.Add(2);

list2.Add(2);
list2.Add(3);

var list3 = from l1 in list1 from l2 in list2 where l1 == l2 select l1;

foreach(var i in list3)
Console.WriteLine(i);
caoyuanlangzi001 2010-08-08
  • 打赏
  • 举报
回复
那如何做到相对完善些呢?
onenewsmile 2010-08-08
  • 打赏
  • 举报
回复
这样写有问题吧,a[i].Equals(b[i]),只有元素位置对应时才判断有交集,这不合交集定义吧,估计要写两层循环。
Peter200694013 2010-08-08
  • 打赏
  • 举报
回复
你写的方法不对吧

在for循环中你只是比较a[i] ,b[i]是否相等 如果a[0] 和 b[3]相等,你考虑了么?

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧