简体   繁体   English

比较两个int列表

[英]Compare two int lists

I have an object that looks like this: 我有一个看起来像这样的对象:

public class TestObject {

        private string name = string.Empty;
        private List<int> ids;

        public TestObject(List<int> ids, string name)
        {
            this.ids = ids;
            this.name = name;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public List<int> Ids
        {
            get { return ids; }
            set { ids = value; }
        }

    }

I get a list of of these objects that looks something like this: 我得到这些对象的列表,看起来像这样:

List<TestObject> listTest = new List<TestObject>();
listTest.Add(new TestObject((new int[] { 0, 1, 5 }).ToList(), "Test1"));
listTest.Add(new TestObject((new int[] { 10, 35, 15 }).ToList(), "Test2"));
listTest.Add(new TestObject((new int[] { 55 }).ToList(), "Test3"));
listTest.Add(new TestObject((new int[] { 44 }).ToList(), "Test4"));
listTest.Add(new TestObject((new int[] { 7, 17  }).ToList(), "Test5"));

Then I have several lists of integers like so: 然后我有几个整数列表,如下所示:

List<int> list1 = new List<int>();
list1.Add(0);
list1.Add(1);
list1.Add(5);

List<int> list2 = new List<int>();
list2.Add(4);


List<int> list3 = new List<int>();
list3.Add(7);

List<int> list4 = new List<int>();
list4.Add(55);

What I'd like to do is to be able to check these integers lists against the TestObject list and extract TestObjects that are equal. 我想做的是能够对照TestObject列表检查这些整数列表并提取相等的TestObject。 In other words, in this example list1 would find a hit in the object at position 0, list4 would find a hit in position 2, there is no hit for list3 as there is only a partial in position 4 and there is no hit for list2 as it does not exist. 换句话说,在此示例中,list1将在对象的位置0处找到一个命中,list4将在位置2处找到一个命中,list3没有命中,因为位置4仅存在部分命中,list2没有命中因为它不存在。

I thought first that it could be done with "Except." 我首先想到可以使用“例外”来完成。 So, if there is nothing between the listN and listTest at n position then that is a hit?? 因此,如果listN和lis​​tTest之间在n位置之间什么都没有,那么这是一个成功? The thing is how to compare the listN to the list in the object at position N in listTest?? 问题是如何将listN与listTest中位置N的对象中的列表进行比较?

If you care about the order of the items in the list, then spender 's solution is a good one. 如果您关心列表中项目的顺序,那么支出者的解决方案就是一个不错的选择。

However, if the order of the items does not matter (eg {5, 1, 0} should match {0, 1, 5} ), you could use something like this: 但是,如果项目的顺序无关紧要(例如{5, 1, 0}应该与{0, 1, 5} {5, 1, 0}匹配),则可以使用以下方法:

listTest.Where(t => t.Ids.Count == list4.Count && !t.Ids.Except(list4).Any());

Or even better: 甚至更好:

var list4Hash = new HashSet(list4);
listTest.Where(t => list4Hash.SetEquals(t.Ids));
listTest.Where(lt => lt.Ids.SequenceEqual(someOtherList))

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

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