如何重构以下代码以获得更好的性能?
How to refactor below codes to make better performance?
我如何重构下面的 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);
}
}
}
所以您想根据 ChildId
?
展平所有路径并删除重复项
您可以使用自定义 IEqualityComparer<ClassName>
、SelectMany
和 Distinct
。
例如(假设 Demo
是你的 class):
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 扩展方法中使用此比较器,例如 GroupBy
或 Distinct
:
List<Demo> list = ids
.SelectMany(s => helper.method(s.ID))
.Distict(new DemoComparer())
.ToList();
怎么样:
Dictionary<string, TEST> t = helper.GETID(id)
.ToDictionary(path => path.ChildId, path => path);
如果你真的需要List<TEST>
,你可以这样做:
List<TEST> list = t.Select(kv => kv.Value).ToList();
如果你有太多个元素,你可以依靠并行处理:
Dictionary<string, TEST> dic= helper.GETID(id)
.AsParallel()
.ToDictionary(path => path.ChildId, path => path);
我如何重构下面的 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);
}
}
}
所以您想根据 ChildId
?
您可以使用自定义 IEqualityComparer<ClassName>
、SelectMany
和 Distinct
。
例如(假设 Demo
是你的 class):
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 扩展方法中使用此比较器,例如 GroupBy
或 Distinct
:
List<Demo> list = ids
.SelectMany(s => helper.method(s.ID))
.Distict(new DemoComparer())
.ToList();
怎么样:
Dictionary<string, TEST> t = helper.GETID(id)
.ToDictionary(path => path.ChildId, path => path);
如果你真的需要List<TEST>
,你可以这样做:
List<TEST> list = t.Select(kv => kv.Value).ToList();
如果你有太多个元素,你可以依靠并行处理:
Dictionary<string, TEST> dic= helper.GETID(id)
.AsParallel()
.ToDictionary(path => path.ChildId, path => path);