首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

怎么用linq怎么合并两个list集合

2012-10-29 
如何用linq如何合并两个list集合ListCUserInfo users1 new ListCUserInfo()ListCUserInfo users2

如何用linq如何合并两个list集合
List<CUserInfo> users1 = new List<CUserInfo>();
  List<CUserInfo> users2 = new List<CUserInfo>();
  List<CUserInfo> users3= new List<CUserInfo>();
  List<CUserInfo> users4 = new List<CUserInfo>();
  CUserInfo cuers1 = new CUserInfo() { UserId = 1, UserName = "wdng", LoginIp = "192.168.1.1" };
  CUserInfo cuers2 = new CUserInfo() { UserId = 2, UserName = "dsg", LoginIp = "192.168.1.1" };
  CUserInfo cuers3 = new CUserInfo() { UserId = 3, UserName = "wfvg", LoginIp = "192.168.1.1" };

  CUserInfo cuers4 = new CUserInfo() { UserId = 2, UserName = "erng", LoginIp = "192.168.1.2" };
  CUserInfo cuers5 = new CUserInfo() { UserId = 5, UserName = "wfgg", LoginIp = "192.168.1.2" };
 
  CUserInfo cuers8 = new CUserInfo() { UserId = 8, UserName = "ghhhg", LoginIp = "192.168.1.4" };
  CUserInfo cuers9 = new CUserInfo() { UserId = 9, UserName = "wsffre", LoginIp = "192.168.1.4" };

  users1.Add(cuers1); users1.Add(cuers2); users1.Add(cuers3); 
  users2.Add(cuers4); users2.Add(cuers5); 
  users4.Add(cuers8); users4.Add(cuers9);

两个list集合,不用循环,如何通过linq语句将users1和users2中UserId相同的对象合并起来,比如users1与users2合并后为:
  CUserInfo cuers1 = new CUserInfo() { UserId = 1, UserName = "wdng", LoginIp = "192.168.1.1" };
  CUserInfo cuers2 = new CUserInfo() { UserId = 2, UserName = "dsg", LoginIp = "192.168.1.1" };
  CUserInfo cuers3 = new CUserInfo() { UserId = 3, UserName = "wfvg", LoginIp = "192.168.1.1" };
  CUserInfo cuers5 = new CUserInfo() { UserId = 5, UserName = "wfgg", LoginIp = "192.168.1.2" };

如果两个集合没有相同的userid,就全部合并。如users1与users3合并后为:,用linq语句怎样写?
  CUserInfo cuers1 = new CUserInfo() { UserId = 1, UserName = "wdng", LoginIp = "192.168.1.1" };
  CUserInfo cuers2 = new CUserInfo() { UserId = 2, UserName = "dsg", LoginIp = "192.168.1.1" };
  CUserInfo cuers3 = new CUserInfo() { UserId = 3, UserName = "wfvg", LoginIp = "192.168.1.1" };
  CUserInfo cuers8 = new CUserInfo() { UserId = 8, UserName = "ghhhg", LoginIp = "192.168.1.4" };
  CUserInfo cuers9 = new CUserInfo() { UserId = 9, UserName = "wsffre", LoginIp = "192.168.1.4" };


[解决办法]
class MyComparer : IEqualityComparer<CUserInfo>
 {
public bool Equals(CUserInfo x, CUserInfo y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.UserId == y.UserId;
}

public int GetHashCode(CUserInfo user)
{
return user.UserId.GetHashCode();
}

}


[解决办法]
.ToList()

热点排行