gsiradze gsiradze - 1 year ago 80
C# Question

check if exists in list

I have this model clas:

public class usersInDashboard
public string Name { get; set; }
public string fbID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public int? countOfBid { get; set; }

and here's my controller

var participants = from q in db.firstWeekBids
where q.bidedItem == "laptop"
join w in db.Users
on q.userId equals w.Id
select new { q.bidCount };

var model = new List<usersInDashboard>();

foreach (var prt in participants)
var userDash = new usersInDashboard();
userDash.fbID =;
if (model.Contains((userDash.fbID))
userDash.fbID =;
userDash.firstName =;
userDash.countOfBid = prt.bidCount;
return PartialView(model);

I need to check if this fbID exists in my list. is string which is equal of fbID.
I've tried
if (model.Contains((userDash.fbID))
but it throws an exception

Error 1 The best overloaded method match for
has some invalid arguments C:\Users\John\Documents\visual studio
2013\Projects\BlaBlaBla\BlaBlaBla\Controllers\AuctionController.cs 67 21

How can i do that?

Answer Source

Contains method determines whether a sequence contains a specified element by using the default equality comparer, if you didn't create a custom one. If you want to know, whether any element of a sequence exists with the specified data, then use Any() overload with predicate instead of Contains():

model.Any(x => x.fbID == userDash.fbID);

If you still want to use Contains, then either you can create your own comparer or your model should implement the System.IEquatable. Or try @teovankot answer.

But, as I said if you want to determine if any element in a collection matches a certain condition then you must use Any().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download