[英]Distinct using Linq query
每個InfringementEntity都有一個類型。
foreach (InfringementEntity ie in _infCol.InfCollection.Select(r=>r).Distinct())
{
InfringementLodgementEntity.InfringementCollection.InfCollection.Add(ie);
}
InfringementLodgementCollection.InfringementLodgementEntities
.Add(InfringementLodgementEntity);
我需要選擇所有具有不同類型的侵權實體並將其插入新的InfringementLodgementEntity中。 然后在InfringementLodgementCollection中添加此InfringementLodgementEntity。
問題是如何選擇不同類型的infringementEntity,將它們添加到新的InfringementLodgementEntity中。
您應該實現IEqualityComparer<InfringementEntity>
檢查類型,並使用接受這種比較器的Distinct
重載。
如果我理解您的問題,則可以使用OfType() 。
var theInfringementEntitiesYouWant = _infCol.InfCollection.OfType<TheTypeYouWant>().Distinct();
我省略了.Select(r=>r)
因為它沒有做任何有用的事情。
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;
}
}
我發現處理此問題的最簡單方法是,在基類中只有一個抽象方法GetType(),根據定義,該方法必須在繼承的類中被覆蓋。
反射是相當昂貴的,在大多數情況下應謹慎使用。 因此,當我們使用它時,我們只是存儲反射的結果。
然后,我們可以這樣做:
var entities = _infCol.InfCollection.Where(w => w.GetType() == typeof(DesiredType) );
從這里您可以做您想做的事情,可以將其大量插入另一個集合中,也可以執行其他操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.