2015-11-09 45 views
-1

我如何重构我的下面的C#代码,使我的过程更好的性能?如何重构以下代码以获得更好的性能?

var list= new List<TEST>(); 
foreach(var id in ids) 
{ 
    var list1= helper.method(id); 

    foreach(var path in list) 
    { 
     var match = list1.Any(s => s.ChildId == path.ChildId); 
     if (!match) 
     { 
      list1.Add(path); 
     } 
    } 
} 
+1

什么是您的探查说?离你的表现目标有多远? – Richard

+4

我投票结束这个问题作为题外话,因为这个问题属于CodeReview.SE。 –

回答

1

如何:

Dictionary<string, TEST> t = helper.GETID(id) 
                   .ToDictionary(path => path.ChildId, path => path); 

如果您确实需要List<TEST>,你可以这样做:

List<TEST> list = t.Select(kv => kv.Value).ToList(); 

如果你有太多元素,你可以依靠paralell处理:

Dictionary<string, TEST> dic= helper.GETID(id) 
                  .AsParallel() 
                  .ToDictionary(path => path.ChildId, path => path); 
+0

“ids”(原'serNos')中每个项目的一本词典? –

1

所以你想要平坦化所有的路径,并删除重复项根据ChildId

您可以使用自定义的IEqualityComparer<ClassName>SelectManyDistinct

例如(假设Demo是类):

public class Demo 
{ 
    public int ID { get; set; } 
} 

public class DemoComparer : IEqualityComparer<Demo> 
{ 
    public bool Equals(Demo x, Demo y) 
    { 
     if (Object.ReferenceEquals(x, y)) return true; 
     if (x == null || y == null) return false; 
     return x.ID == y.ID; 
    } 

    public int GetHashCode(Demo obj) 
    { 
     return obj.ID; 
    } 
} 

现在你可以在很多LINQ扩展方法使用该比较器像GroupByDistinct

List<Demo> list = ids 
    .SelectMany(s => helper.method(s.ID)) 
    .Distict(new DemoComparer()) 
    .ToList(); 
相关问题