2013-04-23 1 views
20

私は以下のコードをc#4.0に用意しています。リスト<Object> Linqを使用して最初のオブジェクトを取得する方法

//Dictionary object with Key as string and Value as List of Component type object 
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>(); 

//Here I am trying to do the loping for List<Component> 
foreach (List<Component> lstComp in dic.Values.ToList()) 
{ 
    // Below I am trying to get first component from the lstComp object. 
    // Can we achieve same thing using LINQ? 
    // Which one will give more performance as well as good object handling? 
    Component depCountry = lstComp[0].ComponentValue("Dep"); 
} 
+0

http://stackoverflow.com/questions/8886796/linq-firstordefault – Satpal

+0

この条件コンポーネントdepCountry = lstComp [0] .ComponentValue( "発")をチェックする方法。まず、lstComp [0]コンポーネントからComponentオブジェクトを取得する方法が簡単なので、コンポーネントにはコンポーネントがあります。 –

+0

'ToList()'を 'Values'にドロップする必要はなく、余分なオブジェクトの作成と全体の値のコレクション。 –

答えて

41

試してください:あなたはまた、任意の項目を含んでいないlstComp場合にだけFirstOrDefault()を使用することができます

var firstElement = lstComp.First(); 

http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx

編集:

Component Valueを取得するには:

var firstElement = lstComp.First().ComponentValue("Dep"); 

これはlstCompの要素があるとします。
.First .FirstOrDefault .Single .SingleOrDefault
を選択して最高のあなたにぴったり:代替、より安全な方法は、そのような方法の束があります

var firstOrDefault = lstComp.FirstOrDefault(); 
if (firstOrDefault != null) 
{ 
    var firstComponentValue = firstOrDefault.ComponentValue("Dep"); 
} 
+1

.ComponentValue( "Dep")フィールドから返されるコンポーネントが必要です。つまり、lstComp [0]フィールドには、オブジェクトのコンポーネントタイプも含まれます。 –

+0

@ManojSingh - lstComp.First()を実行できます。ComponentValue( "Depature"); –

+0

@ManojSingh - 私の答えを –

0

...だろう。

+0

。Take(1)も同様に動作します – jle

+0

@jleいいえ、IEnumerable を返します。 – ken2k

+0

それは最初の要素だけを含んでいますが、OPの質問ごとに '最初のオブジェクト'ではないと思います。 – jle

1

また、これを使用することができます:

var firstOrDefault = lstComp.FirstOrDefault(); 
if(firstOrDefault != null) 
{ 
    //doSmth 
} 
4

[0].First()はあなたに起こるものは何でも同じ性能が得られます。
DictionaryList<Component>の代わりにIEnumerable<Component>が含まれていて、[]演算子を使用できない可能性があります。それは違いが大きいところです。あなたの例のためにそう

は、それが本当に重要ませんが、このコードでは、最初に()を使用する選択肢がない:

var dic = new Dictionary<String, IEnumerable<Component>>(); 
foreach (var components in dic.Values) 
{ 
    // you can't use [0] because components is an IEnumerable<Component> 
    var firstComponent = components.First(); // be aware that it will throw an exception if components is empty. 
    var depCountry = firstComponent.ComponentValue("Dep"); 
} 
+0

なぜToList()の値は? –

0
var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep")); 
0

最初にすべてのリストを取得し、これを試してみてください、その後、ご希望の要素は、(あなたのケースでは初と言う):

var desiredElementCompoundValueList = new List<YourType>(); 
dic.Values.ToList().ForEach(elem => 
{ 
    desiredElementCompoundValue.Add(elem.ComponentValue("Dep")); 
}); 
var x = desiredElementCompoundValueList.FirstOrDefault(); 

はforeachの反復や変数の割り当てがあまりなく、直接最初の要素の値を取得するには

var desiredCompoundValue = dic.Values.ToList().Select(elem => elem.CompoundValue("Dep")).FirstOrDefault(); 

2つのアプローチの違いを参照してください。最初のものでは、ForEachを経てリストを取得します。 2番目の方法では、あなたの価値をまっすぐに得ることができます。

同じ結果、異なる計算;)

+0

これらの答えは両方とも 'ToList() 'の使用のために値のコレクション全体を列挙する必要があります。 –

+0

確かに、彼はPerformace問題なしでDictionary of Listを使用しているので正しいと思います。違いはサイクルにあり、2番目の解決策は私には優れています。 「軽い」ものに合うようにコードを修正することは、たとえメモリ情報に保存するより良い方法に同意しても、このケースでは時間の損失になります。私は全体のふるまいを表現するプロパティを持つ少なくとも2つのクラスを参照してください!よろしく。 –

+0

2番目の例は失敗しません。 'FirstOrDefault'へのパラメータは、select関数ではなくboolを返すフィルタ関数を必要とします。 –

0

私はこのようにそれをするためになります

//Dictionary object with Key as string and Value as List of Component type object 
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>(); 

//from each element of the dictionary select first component if any 
IEnumerable<Component> components = dic.Where(kvp => kvp.Value.Any()).Select(kvp => (kvp.Value.First() as Component).ComponentValue("Dep")); 

が、そのリストがのみコンポーネントクラスのオブジェクトや子供

+0

ディクショナリをそのように定義しているため、コンポーネントまたはその子しか持てません! –

+0

はい、私の例ではあります。 linq文で 'as '演算子を不適切に使用すると危険であり、アプリケーションがクラッシュする可能性があるため、ノートを残す必要があると感じます。しかし、あなたは正しいです - この場合は明らかです。 – Sarrus

1

が含まれていることを確認されている場合のみlinq式は次のように使用できます:

List<int> list = new List<int>() {1,2,3 }; 
     var result = (from l in list 
        select l).FirstOrDefault(); 

ラムダあなたはこのように使うことができます。

List list = new List(){1、2、3}; int x = list.FirstOrDefault();

1

あなたは値の辞書全体のためにこれを望んでいるならば、あなたもこれはあなたに新しい辞書を与えるバックキー

var newDictionary = dic.Select(x => new 
      { 
       Key = x.Key, 
       Value = x.Value.Select(y => 
         { 
          depCountry = y.ComponentValue("Dep") 
         }).FirstOrDefault() 
      } 
      .Where(x => x.Value != null) 
      .ToDictionary(x => x.Key, x => x.Value()); 

にそれを結ぶことができますまた

Component depCountry = lstComp 
         .Select(x => x.ComponentValue("Dep")) 
         .FirstOrDefault(); 

を行うことができます。値にアクセスできます

var myTest = newDictionary[key1].depCountry  
0

私はそうしています。

List<Object> list = new List<Object>(); 

if(list.Count>0){ 
    Object obj = list[0]; 
} 
+0

あなたのソリューションをはっきり説明してください – daniele3004

関連する問題