0

I am trying to check if one exists before adding but casting within .Any does not work.

People is ObservableCollection of objects because each can be different class (each has FirstLastName property).

ObservableCollection<object> People = new ObservableCollection<object>();

foreach (cEmployee t in Group1)
{
  if (!People.Any((cEmployee)x => x.FirstLastName == t.FirstLastName) 
      People.Add(new cEmployee(t));              
}

Is there a workaround?

dee-see
  • 23,668
  • 5
  • 58
  • 91
Daniel
  • 1,064
  • 2
  • 13
  • 30

2 Answers2

5

If they are all guaranteed to have a FirstName property one option is to use dynamic

if (!People.Any((dynamic x) => x.FirstName == t.FirstName)) { 
  ...
}

This isn't type safe but will function if all values do indeed have the property. If on the other hand they all implement a common base type or interface with the FirstName property then you can use that

if (!People.OfType<TheType>().Any(x => x.FirstName == t.FirstName)) { 
  ...
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

Are you sure you need to call People.Add(new cEmployee(t)), and not People.Add((cEmployee)t) or even just People.Add(t) ?

Martin
  • 920
  • 7
  • 24