2016-10-07 10 views
2

私は、解析されたテストの実行から情報を保持する辞書を持っています。キーはメソッドの名前で、値はTestRunPropertiesのリストです。私の辞書には、テスト実行のすべてのメソッドが含まれており、テストの実行中に失敗したメソッドを削除したいと考えています。 Linqとこれは可能ですか?辞書C#からLinqで特定の値を削除する

TestRunPropertiesクラス:

public class TestRunProperties 
{ 
    public string computerName { get; set; } 
    public TimeSpan duration { get; set; } 
    public string startTime { get; set; } 
    public string endTime { get; set; } 
    public string testName { get; set; } 
    public string outcome { get; set; } 
} 

辞書:

//Key is the name of the method, value is the properties associated with each run 
private static Dictionary<string, List<TestRunProperties>> runResults = new Dictionary<string, List<TestRunProperties>>(); 

私はこれを試してみたが、私はWhere一部と混同しそうだと思う:

runResults.Remove(runResults.Where(methodName => methodName.Value.Where(method => method.outcome.ToLower().Equals("failed")))); 

私は」 LinqとLambdaにとってはまったく新しく、私はまだこのようなデータへのアクセス方法を理解しようとしています。

+0

、あなたの助けのためにすべて本当に素晴らしい答えをありがとうございました! – Novastorm

答えて

3

ただループを使って、不要な項目を削除してください。あなたは呼び出しやすくするために拡張メソッドを書くことができます:

public static class DictionaryExt 
{ 
    public static void RemoveAll<K, V>(this IDictionary<K, V> dict, Func<K, V, bool> predicate) 
    { 
     foreach (var key in dict.Keys.ToArray().Where(key => predicate(key, dict[key]))) 
      dict.Remove(key); 
    } 
} 

これは通常、削除されるアイテムの数がのサイズに比べて相対的に低い場合は特に、完全に新しい辞書を作成するよりも効率的になります辞書。

あなたの呼び出し元のコードは次のようになります。

runResults.RemoveAll((key, methodName) => methodName.Value.Where(method => method.outcome.ToLower().Equals("failed"))); 

を(私はList.RemoveAll()と一致する名前RemoveAll()を選択しました。)

0

あなたはおそらく、既存のものから新しい辞書を選択する方がいいでしょう正直に言うと:

runResults.Select().ToDictionary(x => x.Key, x => x.Value.Where(x => x.Value.outcome != "failed")); 

*辞書にリストを反映してeditted。

runResults.Select(x => new { x.Key, x.Value.Where(x => x.Value.outcome != "failed")}).Where(x => x.Value.Any()).ToDictionary(x => x.Key, x => x.Value); 
+0

私は上記に欠けている部分があると思います。値は個々のTestRunPropertyではなくリストです。その結果から.outcomeにアクセスすることはできません – Novastorm

+0

ああ、もう1つのレベルをクエリする必要があります – gmn

1

を無効なものをフィルタリングすることで、新しい辞書を作成することができます::実は、あなたもこれを行うことによって成功していない結果を持つものを取り除くことができます

var filtered = runResults.ToDictionary(p => p.Key, p => p.Value.Where(m => m.outcome.ToLower() != "failed").ToList()); 

[OK]を、grrrrrrはより速いです:-)

+0

ありがとうございました! grrrrrr答えは近かったが、1点か2点を逃した:) – Novastorm

関連する問題