简体   繁体   English

如何比较两个列表,ASP.net

[英]How to compare two list,ASP.net

I have two list and wanna know which items are in the fist one and arn't in second one, 我有两个清单,想知道第一项是哪些,第二项却没有,

List<int> viewphonenumid = new List<int>();
List<int?> DtoPhonenumId = new List<int?>();

For instance viewphonenumid has {1,2,3,4,5,6} and DtoPhonenumId has{3,4,5,6} and I wanna have {1,2} in a new list. 例如,viewphonenumid具有{1,2,3,4,5,6}而DtoPhonenumId具有{3,4,5,6},而我想在新列表中具有{1,2}。

var newList= viewphonenumid.Except(DtoPhonenumId).ToList();

You also can specify comparer. 您也可以指定比较器。

http://msdn.microsoft.com/library/bb336390(v=vs.110).aspx http://msdn.microsoft.com/library/bb336390(v=vs.110).aspx

也许是这样的:

var newList= viewphonenumid.Where(v =>! DtoPhonenumId.Contains(v)).ToList();

I suggest you to use Enumerable.Except http://msdn.microsoft.com/ru-ru/library/bb300779(v=vs.110).aspx 我建议您使用Enumerable。除了http://msdn.microsoft.com/ru-ru/library/bb300779(v=vs.110).aspx

Something like this 像这样

(new List<int> {1,2,3,4}).Except(new List<int> {3,4})

try following: 尝试以下操作:

List<int> result = new List<int>();
foreach(int element in viewphonenumid)
    if(!DtoPhonenumId.Contains(element))
        result.Add(element);

I hope that help 我希望有帮助

If you want to compare two list of items in C#, You should use Enumerable.SequenceEqual method. 如果要比较C#中的两个项目列表,则应使用Enumerable.SequenceEqual方法。

List<int> list1 = new List<int>();

list1.Add(7);
list1.Add(5);
list1.Add(9);

List<int> list2 = new List<int>();

list2.Add(7);
list2.Add(5);
list2.Add(9);

if (list1.SequenceEqual(list2))
{
     //lists are identical
}
else
{
     // lists have different items
}

LINQ has a pretty good algorithm for that. LINQ为此有一个很好的算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM