gsiradze gsiradze - 1 month ago 11
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 = user.id;
if (model.Contains((userDash.fbID))
{
...
}
else
{
userDash.fbID = user.id;
userDash.firstName = user.name;
userDash.countOfBid = prt.bidCount;
model.Add(userDash);
}
}
return PartialView(model);


I need to check if this fbID exists in my list. user.id 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
'System.Collections.Generic.List.Contains(BlaBlaBla.Models.usersInDashboard)'
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

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().

Comments