I am working on an existing solution. Where I have two entities like
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; }
}
and also have one ViewModel
public class UserAccountViewModel
{
public long AccountId { get; set; }
public string AccountNo { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
}
Now, how can I get List<UserAccountViewModel>
from those entities?
var UserAccountViewModel = (from Account in list1
join UserAccountViewModel in list2
on Account .AccountNo equals UserAccountViewModel.AccountNo
select new { UserAccountViewModel }).ToList();
Hope it helps you. Or to increase the performance as per suggestion
var query = dataContext.UserAccountViewModel
.Include(o => o.Account)
.Where(t=> t.AccountNo == t.Account.AccountNo).ToList();
If you have two lists of accnouts and users from which you want to create List, you can use:
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();
At last I get my answer.It's something like below example:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.