First off,
drank
is out of scope by the time your code gets to the end of the
foreach
loop - so no matter what it was, you can't use it - it no longer exists.
Secondly, Contains and IndexOf require a class that implements IEnumerable<T> so unless the
bier
class is actually a derived from a List or similar, or you added a Contains method to it yourself, you can't call it. And from the code above that, I don't think it is.
This is what you are trying to do, I think:
public class Beer
{
public string Name { get; set; }
public int Abv { get; set; }
}
private void MyButton_Click(object sender, EventArgs e)
{
List<Beer> beers = new List<Beer>();
Beer a = new Beer() { Name = "Shimptons Old Cleanser", Abv = 17 };
beers.Add(a);
Beer b = new Beer() { Name = "Horse Urine", Abv = 3 };
beers.Add(b);
Beer c = new Beer() { Name = "Heinekon", Abv = 1 };
beers.Add(c);
if (beers.Contains(b))
{
Console.WriteLine("Yes, {0} is a beer. Technically.", b.Name);
}
Console.WriteLine("{0} is at index {1}", c.Name, beers.IndexOf(c));
...
Quote:</div>well sort off, i want to check a value (int) that comes from a sql database. but where can i use the contain method to check if there is an number for example 100 in my database.
Basically, don't.
If you want to know if something exists in a DB, ask the DB!
SELECT COUNT(*) FROM MyTable WHERE MyColumn = 100
Use that with ExecuteScalar, and it will return the number of items with that value.
If you have built them into a collection of
bier
objects, then use the Linq Exists method instead:
if (beers.Exists(x => x.Abv = 3))
{
Console.WriteLine("Yes, {0} is a beer. Technically.", b.Name);
}
The Contains method only looks for an exact match on an object reference to an object reference in the collection, it can't look at the object internals.