我的问题是如何加入具有相同ID但不同联系人的选定行
这是我正在做的的输出
| Name | Address | Cellphone | Email |
| John | NY | n/a | johndoe@y.c |
| John | NY | 123456781 | n/a |
我希望我的输出是一个线性组合
| Name | Address | Cellphone | Email |
| John | NY | 123456781 | johndoe@y.c |
这是我的林克
var an = (from a in db.Info
join b in db.Contact
on a.ID equals b.InfoID
where b.ContactTypeID == 56
|| b.ContactTypeID == 59
select new
{
a.ID,
a.LastName,
a.FirstName,
a.MiddleName,
b.ContactTypeID,
b.Values
}).ToList();
List<Info> wlist = new List<Info>();
foreach (var row in an)
{
Info ci = new Info
{
ID = row.ID,
Name = row.FirstName + " " + row.MiddleName + " " + row.LastName,
ContactType = GetLookupDisplayValById(row.ContactTypeID),
ContactValue = row.Values
};
wlist.Add(ci);
}
return Json(wlist.ToList(), JsonRequestBehavior.AllowGet);
}
我希望有人能帮我做这个
感谢:)
你可以做到:
from info in db.Info
join contact in db.Contact
on info.ID == contact.InfoID
select new Contact(info, contact)
并且您的构造函数将合并。
public class Contact
{
public int ID { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public int ContactTypeID { get; set; }
public Contact(Info info, Contact contact)
{
ID = info.ID;
LastName = string.IsNullOrEmpty(info.LastName) ? contact.LastName : info.LastName;
}
}
尝试GroupBy
var resuts = db.Info.GroupBy(i=>i.ID)
.Select(g=>new Info{
ID = g.Key,
Address = g.Fist().Address,
Cellphone = g.FistOrDefault(x=> x.Cellphone !="n/a"),
Email = g.FistOrDefault(x=> x.Email !="n/a")
}).ToList();