简体   繁体   English

如何在列表中使用 IndexOf<object[]> ?</object[]>

[英]How can I use IndexOf in a List<object[]>?

If I declare a List like,如果我声明一个类似的列表,

List<object[]> People = new List<object[]>();

(in which object[] has two elements) (其中object[]有两个元素)

People.Add(new object[] {"Sam", 18});

Is there a way I can find the index of a person like this?有没有办法可以找到这样的人的索引?

People.IndexOf(new object[] {"Sam", 18});

I've tried doing it like it is above, but it returns -1 .我试过像上面那样做,但它返回-1


Solved this in my own crappy way by creating an extension method which takes a string parameter and loops through the list until it matches with one, then returns that index.通过创建一个扩展方法以我自己的糟糕方式解决了这个问题,该方法接受一个字符串参数并遍历列表,直到它与一个匹配,然后返回该索引。

public static int OIndexOf(this List<object[]> List, string Check)
{
    for (int I = 0; I < List.Count; I++)
    {
        if ((string)List[I][0] == Check)
            return I;
    }
    return -1;
}

Generally speaking, you're going to need a concrete type to make this work, like a Person object or an int value.一般来说,你需要一个具体的类型来完成这项工作,比如Person object 或int值。

The reason this is the case is because your type must implement an .Equals() method.出现这种情况的原因是您的类型必须实现.Equals()方法。 It won't work with object objects, because the.Equals method for object compares references, not values, and your comparison will always return false unless you have the original object (not the case in your code, where you're creating a new object for comparison.它不适用于object对象,因为 object 的object方法比较引用,而不是值,并且您的比较将始终返回false除非您拥有原始object (不是您的代码中创建new的情况) object 用于比较。

From the documentation for the IndexOf method :IndexOf 方法的文档

This method searches all the elements of a one-dimensional array for value.此方法搜索一维数组的所有元素以获取值。 To determine whether value exists in array, the method performs an equality comparison by calling each element's Equals method until it finds a match.为了确定值是否存在于数组中,该方法通过调用每个元素的 Equals 方法执行相等比较,直到找到匹配项。 This means that if the element overrides the Object.Equals(Object) method, that override is called.这意味着如果元素覆盖 Object.Equals(Object) 方法,则调用该覆盖。

Therefore, you need a Person object with an Equals() override.因此,您需要一个带有Equals()覆盖的Person object。 To wit:以机智:

public class Person
{
    public string Name { get; set; }

    public override bool Equals(Person other)
    {
        return Name.Equals(other.Name);
    }
}

If you want to compare an array of people, you need another type that encapsulates your Person array, and an Equals() method to check equality of every person in the array with every person in the other array.如果你想比较一个人数组,你需要另一种封装你的 Person 数组的类型,以及一个 Equals() 方法来检查数组中的每个人与另一个数组中的每个人的相等性。

If you had a reference to the actual array you wanted to look for then IndexOf would work in the way you want.如果您引用了要查找的实际数组,那么IndexOf将以您想要的方式工作。 But you are creating a new array, so it won't work.但是您正在创建一个新数组,所以它不起作用。

The simplest way to do what you want is to use FindIndex :做你想做的最简单的方法是使用FindIndex

People.FindIndex(p => p[0] == "Sam" && p[1] == 18)

To compare to the whole of an array in a variable at the same indices, use LINQ's SequenceEqual要与变量中相同索引处的整个数组进行比较,请使用 LINQ 的SequenceEqual

var arr = new object[] {"Sam", 18};
People.FindIndex(p => arr.SequenceEqual(p));

If you really want to do it, you have to do it yourself.如果你真的想做,你必须自己做。

Example: Create a new function:示例:新建一个 function:

int NewIndexOf(people, item)
{
    int index = 0;
    if(people.length) < 2
        return -1;

    foreach(var p in people)
    {
        p[0].Equals("Sam") && p[1].Equals(18)
        return index;
        ++index;
    }
    return -1;
}

Well, IndexOf uses the default equality comparer for a given type - Object , which is in your case comparers references .好吧, IndexOf使用给定类型的默认相等比较器 - Object ,在您的情况下是 comparers references You have two new - two different referencies, which in turn means that both instances are considered unequal.您有两个new -两个不同的引用,这反过来意味着两个实例被认为是不相等的。 To solve the problem you can:要解决问题,您可以:

Implement your own class:实现您自己的 class:

 public class Person : IEquatable<Person> {
   public Person(string name, int age) {
     if (null == name)
       throw new ArgumentNullException(nameof(name));
     if (age < 0)
       throw new ArgumentOutOfRangeException(nameof(age));

     Name = name;
     Age = age;
   }

   public String Name {get;}

   public int Age {get;}

   public bool Equals(Person other) =>
     other != null && other.Name == Name && other.Age == Age;

   public override bool Equals(Object o) => Equals(o as Person);

   public override int GetHashCode() => Name.GetHashCode() ^ Age;
 }

Then you can put然后你可以把

 List<Person> People = new List<Person>();

 People.Add(new Person("Sam", 18));

 // Now .NET knows how to compare Person instances
 int index = People.IndexOf(new Person("Sam", 18));

Another approach (not a good practice, though) is to find index manually, with a help of LINQ :另一种方法(虽然不是一个好的做法)是在LINQ的帮助下手动查找index

 List<object[]> People = new List<object[]>();

 ...

 var index = People
    .Select((v, i) => new { v, i })
    .FirstOrDefault(pair => pair.v.SequenceEqual(new object[] { "Sam", 18 }))
   ?.i ?? -1;

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

相关问题 如何使用 List 的 IndexOf() 方法<object> - How to use IndexOf() method of List<object> 如何使用 indexof 和 substring 从字符串中提取数字并制作列表<int>的数字?</int> - How can I use indexof and substring to extract numbers from a string and make a List<int> of the numbers? 我如何使用IndexOf查找完全匹配? - How can i use IndexOf to find an exact match? 如何使用 indexof 和 substring 在字符串中查找单词? - How can I use indexof and substring to find words in a string? 名单 <string> object IndexOf返回-1。 怎么样? - List<string> object IndexOf returning -1. How? 如何不区分大小写地使用indexOf()? - How do I use indexOf() case insensitively? 我如何解析字符串中的文本并将其添加到列表中 <string> 使用indexof和substring? - How can i parse text from string and add it to a List<string> using indexof and substring? 如何使用String.IndexOf方法找到正确的值? - how can I use String.IndexOf method to find the correct value? 如果有多个字符,我该如何使用IndexOf来选择一个特定字符? - How can I use IndexOf to pick a specific Character when there are more than one of them? 如何使用indexof和substring和string.format在文本的特定位置添加随机数/文本? - How can I use indexof and substring and string.format to add random numbers/text in specific place in text?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM