Question

I have a list which is created from a Class:

class Vara
{
    public int streckKod { get; set; }
    public string artNamn { get; set; }
}

And the list looks like this:

List<Vara> minaVaror = new List<Vara>();

And I add to the list with this line:

minaVaror.Add(new Vara() {streckKod = inputBox1, artNamn = textBox2.Text });

But what I'm stuck at is how I can find a specific int within the list. Let's say I'm searching for the item in my list holding the number 293 in the variable streckKod.

I've tried using .IndexOf function but I haven't gotten it to work properly.

Also would it be possible to get the item number that the specific number is located in?

Was it helpful?

Solution

If you want to find all items whose streckKod value is 293 use Where

var items = minaVaror.Where(i => i.streckKod == 293);

If interested in only first item use FirstOrDefault -

var item = minaVaror.FirstOrDefault(i => i.streckKod == 293);

FirstOrDefault will return null in case no item exist in collection with value 293.

Make sure you add namespace System.Linq in your class to use these LINQ extension methods.

OTHER TIPS

Use Linq

minaVarror.Find(item=>item.strekKod == 293);

Adding to Rohit Vats answer...

When you have found your item, with either Where or FirstOrDefault you can get the index by doing:

var item = minaVaror.FirstOrDefault(i => i.streckKod == 293);

// Get index of Vara (item) with streckKod = 293
int index = minaVaror.IndexOf(item);

As IndexOf returns the position of an exact item (Vara) within the list minaVaror

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top