读书人

一个有关Listlt;Tgt;中元素替换的有关问题

发布时间: 2013-09-06 10:17:17 作者: rapoo

一个有关List<T>中元素替换的问题
现在我有两个类


//trans
public class Trans
{
public string name;
public double fix_x;
public double fix_y;
public Trans(string a, double b, double c)
{
this.name = a;
this.fix_x = b;
this.fix_y = c;
}
}
//Nails
public class Nails
{
public string name;
public string nail;
}

这两个类分别用List<Trans>和List<Nails>装起来的,现在我要将List<Trans>中的name替换成List<Nails>中的nail,我写了一个实现方法,但是不知道为什么返回的还是原来的List<Trans>,求解!

public static List<Trans> change(List<Trans> a,List<Nails> b)
{
List<Trans> Transf_new = new List<Trans>();
Trans nail_new;

foreach (Trans nail in a)
{
string c = nail.name;
foreach (Nails net in b)
{
if (nail.name == net.nail)
c = net.name;
}


nail_new = new Trans(c, nail.fix_x, nail.fix_y);
Transf_new.Add(nail_new);
}
return Transf_new;
}

class list
[解决办法]
or use linq:
List<Trans> trans = new List<Trans>();
trans.Add(new Trans("a1", 200, 300));
trans.Add(new Trans("a2", 1200, 1300));

List<Nails> nails = new List<Nails>();
nails.Add(new Nails("name1", "a1"));
nails.Add(new Nails("name2", "a2"));

var result = from p in trans
from q in nails
where p.name == q.nail
select new { q.name, p.fix_x, p.fix_y };
result.ToList().ForEach((x) =>
{
Console.WriteLine("name:" + x.name + " fix_x:" + x.fix_x + " fix_y:" + x.fix_y);


});


[解决办法]
本帖最后由 caozhy 于 2013-08-28 00:16:45 编辑 public static List<Trans> change(List<Trans> a,List<Nails> b)
{
return a.Join(b, x => x.name, y => y.name, (x, y) => new Trans(y.name, x.fix_x, x.fix_y)).ToList();
}

能用join就用join
join的原理是分别计算作为连接字段的hash,并且放入hash表中,所以它的算法复杂度是O(NlogN)
而你的写法包括ls的,相当于2层循环,复杂度是O(N^2)。

读书人网 >C#

热点推荐