【问题标题】:Distinct using Linq query使用 Linq 查询区分
【发布时间】:2011-03-07 10:18:22
【问题描述】:

每个 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 中。

【问题讨论】:

    标签: c# .net linq linq-to-entities


    【解决方案1】:

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

    【讨论】:

    • 我不想排除重复项,只需要他们将它们添加到不同的集合中
    【解决方案2】:

    如果我理解您的问题,您可以使用OfType()

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

    我省略了.Select(r=&gt;r),因为它没有做任何有用的事情。

    【讨论】:

      【解决方案3】:
      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) );
      

      从这里你可以做你想做的事,批量插入另一个集合或其他任何东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-17
        • 1970-01-01
        • 2013-12-02
        • 1970-01-01
        • 2011-07-16
        • 1970-01-01
        • 1970-01-01
        • 2018-10-11
        相关资源
        最近更新 更多