Surya Matadewa
Surya Matadewa

Reputation: 1027

Get indexes from list<>

hi i have this following code in my project

class CVote
{
    public int id;
    public int studentId;
    public string answer;
    public int questionIndex;
    //public DateTime occurred;
}

public static List<CVote> votes = new List<CVote>();

I want to get indexes of certain studentID (ex : studentID 15) so i try this following code

int test = -1;
test = Global.votes.IndexOf(15);

but it's end with error result

  1. Invalid argument
  2. Can't convert from int to CVote

any idea how to do it correctly?

Upvotes: 0

Views: 86

Answers (3)

tchrikch
tchrikch

Reputation: 2468

Try this (to have IndexOf)

var element = Global.votes.SingleOrDefault(e=>e.id==15);
if(element!=null)
 {
  var index = Global.votes.IndexOf(element);
 }

or use FindIndex to have it directly

public static bool Find15(CVote vote){
  if(vote.id==15) return true;
  return false;
}
var index = Global.votes.FindIndex(e=>e.id==15);

Upvotes: 1

Mario Stoilov
Mario Stoilov

Reputation: 3447

IndexOf takes an argument of the same type as the elements in the List(CVote in your example) and returns the index of that element if it finds it, and -1 if it doesn't

Upvotes: 1

L.B
L.B

Reputation: 116178

You need FindIndex

var std = votes.FindIndex(x=>x.id == 15)

Upvotes: 3

Related Questions