tags:

views:

803

answers:

2

I have a list of class items List<MyClass>

I have a seperate object that is of type MyClass

In my list I have an instance of this item but my where statement fails.

var home = Item.Find(23);
var item = allitems.Where(i => i == home);

item yields no results

allitems.Contains(home) also fails.

What am I doing wrong?

+3  A: 

Are they definately tghe same items? If you have this situation;

var item1 = new Place(23);
var item2 = new Place(23);

then item1 != item2. If the items are identified by some property, you could try

allitems.Where(i => i.Id == home.Id)
Steve Cooper
I've done it by ID thanks. Why is item1 considered different than item2 though?
Jon
Because they're different objects. Unless it's overloaded, "==" compares for identity rather than equality - you can have two laptops which are equal in every respect, but they're still distinct laptops for example.
Jon Skeet
Jon's *almost right* ;) == in C# compares the identity of classes, or more correctly reference types. For structs, the values are compared, and the same for basic data types like int. Things that compare that way are called value types.So if you wrote `int x = 7; int y = 7` then `x == y`, because it compares values, but if you wrote`var item1 = new Place(23); var item2 = new Place(23);` `item1 != item2`, because they are two different objects which just happen to have the same content.
Steve Cooper
A: 

Overriding Equals() in "Item" should also work.

var home = Item.Find(23);
var item = allitems.Where(i => i.Equals(home));
Amby