Distinct using Linq query
Every InfringementEntity has a type.
foreach (InfringementEntity ie in _infCol.InfCollection.Select(r=>r).Distinct())
{
InfringementLodgementEntity.InfringementCollection.InfCollection.Add(ie);
}
InfringementLodgementCollection.InfringementLodgementEntities
.Add(InfringementLodgementEntity);
I need to select all Infringement Entity with a different type and insert them in a new InfringementLodgementEntity. And then add this InfringementLodgementEntity in InfringementLodgementCollection.
Question is how would I select infringementEntity with different types add them in a new Infringement开发者_开发问答LodgementEntity.
You should implement an IEqualityComparer<InfringementEntity>
checking for the type, and use the Distinct
overload that is accepting such a comparer.
If I understand your question, you can use OfType().
var theInfringementEntitiesYouWant = _infCol.InfCollection.OfType<TheTypeYouWant>().Distinct();
I left out .Select(r=>r)
because it wasn't doing anything useful.
public abstract class BaseClass
{
private Type _classType;
public Type ClassType
{
get
{
return _classType;
}
set
{
_classType= value;
}
}
public abstract Type GetType();
}
public class InheritedClass: BaseClass
{
public override Type GetType()
{
if (ClassType == null)
{
ClassType = typeof(InheritedClass);//ie SingleInfringement or DblInfringment
}
return ClassType;
}
}
The simplest way I've found to deal with this is just have an abstract method GetType() in your base class which by definition must be overridden in your inherited class.
Reflection is rather expensive and should be used sparingly in most cases. So when we do use it we just store the result of our reflection.
This then allows us to do:
var entities = _infCol.InfCollection.Where(w => w.GetType() == typeof(DesiredType) );
from here you can do what you want, a bulk insert into another collection or whatever.
精彩评论