简体   繁体   English

与Linq查询不同

[英]Distinct using Linq query

Every InfringementEntity has a type. 每个InfringementEntity都有一个类型。

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. 我需要选择所有具有不同类型的侵权实体并将其插入新的InfringementLodgementEntity中。 And then add this InfringementLodgementEntity in InfringementLodgementCollection. 然后在InfringementLodgementCollection中添加此InfringementLodgementEntity。

Question is how would I select infringementEntity with different types add them in a new InfringementLodgementEntity. 问题是如何选择不同类型的infringementEntity,将它们添加到新的InfringementLodgementEntity中。

您应该实现IEqualityComparer<InfringementEntity>检查类型,并使用接受这种比较器的Distinct重载。

If I understand your question, you can use OfType() . 如果我理解您的问题,则可以使用OfType()

var theInfringementEntitiesYouWant =  _infCol.InfCollection.OfType<TheTypeYouWant>().Distinct();

I left out .Select(r=>r) because it wasn't doing anything useful. 我省略了.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;
    }
}

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. 我发现处理此问题的最简单方法是,在基类中只有一个抽象方法GetType(),根据定义,该方法必须在继承的类中被覆盖。

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. 从这里您可以做您想做的事情,可以将其大量插入另一个集合中,也可以执行其他操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM