12 c# linq linq-to-sql c#-4.0 asp.net-mvc-4
以下是上述方法:
public IList<tst> testUsers()
{
IList<tst> testUsers = _test.GetAll().ToList();
return test(test);
}
Run Code Online (Sandbox Code Playgroud)
要显示具有位置的用户,我认为您需要一个名为AdsnapshotUsers的类
public class AdsnapshotUsers
{
// three fields UserId, UserLogonName, Location
}
Run Code Online (Sandbox Code Playgroud)
现在创建一个返回的方法 IList<AdsnapshotUsers>
public IList<AdsnapshotUsers> GetAdsnapshotUsers()
{
List<User> Users = GetAcitveUsers().ToList();
List<ADSnapshot> adSnapshotUsers = _adSnapshotRepository.GetAll().ToList();
return (from u in Users
join ad in adSnapshotUsers on u.UserLogonName equals ad.UserLogonName
select new AdsnapshotUsers {
UserId= u.UserId, UserLogonName = u.UserLogonName, Location = ad.Location
}
).ToList<AdsnapshotUsers>();
}
Run Code Online (Sandbox Code Playgroud)
如果adsnapshot表中没有userlogonname,那么Left Outer Join将显示用户表中的所有值(位置值为空)
(from u in Users
join ad in adSnapshotUsers on u.UserLogonName equals ad.UserLogonName into aduserselect
from ad1 in aduserselect.DefaultIfEmpty()
select new AdsnapshotUsers {
UserId= u.UserId, UserLogonName = u.UserLogonName, Location = ad1.Location
}
).ToList<AdsnapshotUsers>();
Run Code Online (Sandbox Code Playgroud)
此处将显示来自用户表的所有记录,如果存在userlogonname,则选择位置,然后使用ADSnapshot表值设置位置名称值,否则不存在,然后设置默认空值.
在 LINQ 中连接两个 IEnumerable 的最简单方法是使用 Join():
var joined = from u in GetActiveUsers()
join ad in _adSnapshotRepository.GetAll()
on u.UserLogonName equals ad.UserLogonName
select new { User = u, Location = ad.Location }
Run Code Online (Sandbox Code Playgroud)
当然,joined 现在是一个匿名类型的 IEnumerable。如果您在网格视图或需要平面对象的视图中显示此信息,您可能需要使用每个表中所需的属性创建自己的类,然后选择该类。
另外还有两点需要注意:
(1) 你似乎总是尽早调用 ToList() 以从 IQueryable 转换为 IEnumerable。通过推迟 ToList() 直到完成所有连接和过滤,您可以让大部分查询发生在 SQL 中(而不是在内存中)。
(2) 通常最好在实体上设置关联属性并使用这些属性,而不是加入:
IQueryable<User> users = ...
var combinedInfo = users.Select(u => new { User = u, Location = u.ADSnapshot.Location })
.ToList();
Run Code Online (Sandbox Code Playgroud)