score:2

Accepted answer

There are a couple ways you can achieve this. First, you can override Equals for your ViewItem class. This will cause the IndexOf call with a new instance of ViewItem to say that any object you already have in the list is equivalent to a newly created object with the same information. For your class you have listed here is how you could do that:

public class ViewItem
    {
        private int No { get; set; }
        private string Name { get; set; }

        public ViewItem(int no, string name)
        {
            this.No = no;
            this.Name = name;
        }

       public override bool Equals(Object obj)
        {
            // Check for null values and compare run-time types.
            if (obj == null || GetType() != obj.GetType())
                return false;

            ViewItem other = (ViewItem) obj;
            return (No == other.No);
        }

    }

Your example above should return the right index, given that Equals has been overridden. For more information on correctly implementing Equals and GetHashCode see MSDN or http://www.loganfranken.com/blog/687/overriding-equals-in-c-part-1/.

An alternative way to handle this using linq if you are not looking for true equality would be to match on certain properties of your ViewItem class. Here is an example of doing so:

List<ViewItem> items = new List<ViewItem>() { new ViewItem(1, "John"), new ViewItem(2, "Jake"), new ViewItem(2, "Frank")};
var john = new ViewItem(1, "John");
var frankInd = items.FindIndex(i => i.Name == "Frank");
Console.WriteLine(items.IndexOf(john));
Console.WriteLine(frankInd);

score:0

Using LINQ (Enumerable.Cast<TResult> Method):

int IndexMatched = LbxItemBox.Items.Cast<ViewItem>().ToList().FindIndex(x => x.No == ViewX.No);

Related Query