数组重复项的问题
我有这样一个数组
Person[] persons = new Person[4];
persons[0] = new Person() { Id = 1, Name = "Test1", Count = 2 };
persons[1] = new Person() { Id = 2, Name = "Test2", Count = 2 };
persons[2] = new Person() { Id = 1, Name = "Test1", Count = 2 };
persons[3] = new Person() { Id = 3, Name = "Test3", Count = 2 };
重复项是指:ID 和 Name 相同,比如 persons[0] 和 persons[2]
然后把重复项的结果累加
比如,上边的结果是得到一个新的数组,Person[3];
persons[0] = new Person() { Id = 1, Name = "Test1", Count = 4 };
persons[1] = new Person() { Id = 2, Name = "Test2", Count = 2 };
persons[2] = new Person() { Id = 3, Name = "Test3", Count = 2 };
我现在用一个一个比较的方法做的,总感觉效率不高
请问大家有什么好的方法
谢谢了
------解决方案--------------------
static void Main(string[] args)
{
Person[] persons = new Person[4];
persons[0] = new Person() { Id = 1, Name = "Test1", Count = 2 };
persons[1] = new Person() { Id = 2, Name = "Test2", Count = 2 };
persons[2] = new Person() { Id = 1, Name = "Test1", Count = 3 };
persons[3] = new Person() { Id = 3, Name = "Test3", Count = 2 };
var result = from a in persons
from b in persons
where (a.Id == b.Id && a.Name == b.Name) && !a.Equals(b)
select a;
foreach (var a in result)
{
Console.WriteLine("{0},{1},{2}", a.Id, a.Name, a.Count);
}
Console.ReadLine();
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Count { get; set; }
}
------解决方案--------------------
这个很定是要一个一个比较的 用linq 的话就不用 你自己去写算法咯