[英]How to get List of item using join in LINQ?
我正在研究現有的解決方案。 我有兩個實體
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime? DOB { get; set; }
private List<long> _accounts = new List<long>();
[Display(Name = "Account No")]
public List<long> Accounts
{
get { return _accounts; }
set { _accounts = value; }
}
[Display(Name = "Account No")]
public string AccountId
{
get { return string.Join(",", _accounts); }
set { _accounts = value != null ? value.Split(',').Where(s=>!string.IsNullOrWhiteSpace(s)).Select(s => Convert.ToInt64(s.Trim())).ToList() : new List<long>(); }
}
}
public class Account
{
public long Id { get; set; }
public string AccountName { get; set; }
public string AccountNo { get; set; }
}
還有一個ViewModel
public class UserAccountViewModel
{
public long AccountId { get; set; }
public string AccountNo { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
}
現在,如何從這些實體中獲取List<UserAccountViewModel>
?
var UserAccountViewModel = (from Account in list1
join UserAccountViewModel in list2
on Account .AccountNo equals UserAccountViewModel.AccountNo
select new { UserAccountViewModel }).ToList();
希望對您有幫助。 或根據建議提高性能
var query = dataContext.UserAccountViewModel
.Include(o => o.Account)
.Where(t=> t.AccountNo == t.Account.AccountNo).ToList();
如果您有兩個要創建列表的帳戶和用戶列表,則可以使用:
var userAccount = (from account in list1
join user in list2
on account.Id.ToString() equals user.AccountIds
select new UserAccountViewModel
{
AccountId = account.Id,
AccountNo = account.AccountNo,
UserName = user.Name,
UserId = user.Id
}).ToList();
最后我得到了答案,就像下面的例子:
var users = new List<User>{
new User{Id=1 ,Name="Test1",Email="test1@ds.com",DOB=DateTime.Now,AccountId ="1"},
new User{Id=2 ,Name="Test2",Email="test2@ds.com",DOB=DateTime.Now,AccountId ="2"},
new User{Id=3 ,Name="Test3",Email="test3@ds.com",DOB=DateTime.Now,AccountId ="3,4"}
};
var accunts = new List<Account>
{
new Account {Id=1,AccountName = "A",AccountNo = "1"},
new Account {Id=2,AccountName = "B",AccountNo = "2"},
new Account {Id=3,AccountName = "C",AccountNo = "3"},
new Account {Id=4,AccountName = "D",AccountNo = "4"},
};
var userAccounts = (from u in users
from a in accunts
where u.Accounts.Contains(a.Id)
select new UserAccountViewModel
{
AccountNo = a.AccountNo,
AccountId = a.Id,
UserId = u.Id,
UserName = u.Name
}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.