2

私はこのエンティティを持っています:

public class Parent: AllDependant
{
    /*Properties goes here*/
}

public class Children: AllDependant
{
    /*Properties goes here*/
}

次にallDependants、typeofを使用して変数をList<AllDependant>作成します。これにより、親と子のエンティティの一部が混在し続けます。

後で、それらから選択して、次のようなことをしたいと思います。

var selectedDependantInfos = allDependants
        .Select(dependant =>
        {
            if (dependant is Parent)
            {
                var parent = dependant as Parent;
                return new { Name = parent.Name, SomeSpecialInfo = parent.ParentInfo };
            }
            else
            {
                var child = dependant as Children;
                return new { Name = child.Name, SomeSpecialInfo = child.ChildInfo }
            }
        });

子と親の特定のプロパティでは、エンティティに関係のないUI表示用の新しいモデルにプロパティをキャストして取得する必要があることに注意してください。* .ascxを含む非常に多くのファイルでプロパティ名をリファクタリングする必要があるため、AllDependant基本クラスに特別なプロパティを配置できません。これは面倒です。ただし、上記のLinqSelect拡張メソッドを使用して実行しましたが、私はこれについて考えています。

質問:Linqクエリで同じことを行うにはどうすればよいですか?

selectこれにより、キーワードと中括弧にエラーが発生します。

var selectedDependantInfos = from dependant in allDependants
                            select
                            {
                                /* the same if statement goes here */
                            }
4

3 に答える 3

3

条件演算子を使用して、次のようなものを取得します

  from dependant in allDependants             
  select dependant is Parent 
         ? new { Name = (dependant as Parent).Name,  /* Parent fields */ }
         : new { Name = (dependant as Children).Name, /* Child fields */ }

しかし、ご覧のとおり、これは大きな改善ではありません。型キャストを行うのに便利な場所はありません。

より良いオプションは、NameプロパティとSpecialInfoプロパティを基本クラス(AllDependantまたは特別な中間クラス)に移動するように思われます。

于 2012-04-04T06:25:30.140 に答える
2

別の方法は次のとおりです。

var parents = allDependants.OfType<Parent>.Select(p => new { Name =  p.Name, .... };
var children = allDependants.OfType<Children>.Select(c => new { Name =  c.Name, .... };

var combined = parents.Concat(children);

このアプローチの欠点は、addDependantsが2回繰り返されることです。

于 2012-04-04T06:56:07.547 に答える
0

リフレクションを使用する別の方法

var selectedDependantInfos = from p in allDependants
                         let key = p is Parent ? "ParentInfo" : "ChildInfo"
                         select new { 
                             Name = p.GetType().GetProperty("Name").GetValue(p, null).ToString(), 
                             SomeSpecialInfo = p.GetType().GetProperty(key).GetValue(p, null).ToString() 
                         };
于 2012-04-04T07:19:47.993 に答える