How to get List of item using join in LINQ? - c#

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();

Related

Combine two different types into one linq query and sort it

I have two database tables and I'm attempting to create a union query from them. They have different structures:
public partial class Notes
{
public int ID { get; set; }
public int VisitID { get; set; }
public string Note { get; set; }
public DateTime PostDate { get; set; }
public decimal AcctBalance {get; set; }
}
public partial class SystemNotes
{
public int ID {get; set;}
public int VisitID {get; set;}
public int FacilityID {get; set;}
public string Note {get; set;
public DateTime NoteDate {get ;set; }
}
What I want to do is end up with a list of all the data in Notes format sorted by PostDate. What I've tried so far is this:
List<Notes> requests = new List<Notes>();
requests = _context.Notes.Where(i => i.VisitID == VisitID && i.isActive == true).ToList();
List<SystemNotes> requests_s = new List<SystemNotes>();
requests_s = _context.SystemNotes.Where(i => i.VisitID == VisitID).ToList();
var unionA = from a in requests
select new
{
a.ID,
a.VisitID,
a.Note,
a.PostDate,
a.AcctBalance
};
var unionB = from b in requests_s
select new Notes()
{
ID = b.ID,
VisitID = (int)b.VisitID,
Note = b.Note,
PostDate = b.NoteDate,
AcctBalance = (decimal)0.00
};
List<Object> allS = (from x in unionA select (Object)x).ToList();
allS.AddRange((from x in unionB select (Object)x).ToList());
However, PostDate is no longer recognized as an element inside the Object so I can't sort on it. Also, it's in Object format not in Notes format which is what I want for where I'm sending my data. I'm stuck on this one point. Can you assist? Or am I doing this the wrong way in general?
If I correctly understand what you want:
List<Notes> myNotes = new List<Notes> {
new Notes () {
ID = 1,
VisitID = 2
}
};
List<SystemNotes> mySystemNotes = new List<SystemNotes> {
new SystemNotes () {
ID = 3,
VisitID = 4
}
};
var result = myNotes.Select (mn => new { mn.ID, mn.VisitID })
.Union(mySystemNotes.Select (msn => new { msn.ID, msn.VisitID }))
.OrderByDescending(a=>a.ID);
foreach (var currentItem in result)
{
Console.WriteLine ("ID={0}; VisitID={1}", currentItem.ID, currentItem.VisitID);
}

How to get the newly created object inside the .Select() in a LINQ Query

How can I get a reference to the 'parent' object in the Linq below. Something like the way EF does it when you query for objects that are of EF Classes?
void Main()
{
IEnumerable<SomeModel> Brands = ....;
var list = Brands
.Select(b => new BrandModel()
{
ID = b.ID,
BrandName = b.Name,
Locations = b.Locations.Select(l => new LocationModel()
{
ID = l.ID,
LocationName = l.Name,
Brand = *here I would want the Brand object of this Location*
}).ToList()
}).ToList();
}
private class BrandModel
{
public int ID { get; set; }
public string BrandName { get; set; }
public List<LocationModel> Locations { get; set; }
}
private class LocationModel
{
public int ID { get; set; }
public string LocationName { get; set; }
public BrandModel Brand { get; set; }
}
You can create your BrandModel in two steps. First create it without locations, then set locations to it
To do so you need to convert your lambda b => new BrandModel() to block of statements b => { return new BrandModel() }. Try this code:
.Select(b =>
{
var model = new BrandModel
{
ID = b.ID,
BrandName = b.Name
};
model.Locations = b.Locations.Select(l => new LocationModel
{
Brand = model
}).ToList();
return model;
});

How can I get latest employee ID (string) from the list of employees using .net web api Get call

I am using Entity Framework
My EmployeeDto class is :
public class EmployeeDto
{
[DataMember]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SerialNumber { get; set; }
[DataMember]
[Key]
[Required]
public string ID { get; set; }
[DataMember]
[Required]
public string FirstName { get; set; }
[DataMember]
public string MiddleName { get; set; }
[DataMember]
[Required]
public string LastName { get; set; }
}
My Dto class is EmployeeDto and Dal class is named as Employee. I want to get the maximum value of EmployeeID from the database and provide it to frontend through Get call .
My Get call to get the list of all employees is :
public List<EmployeeDto> GetAllEmployees()
{
var employeeDto = new List<EmployeeDto>();
using (EmployeeDataEntities entities = new EmployeeDataEntities())
{
var employeeData = entities.Employees.ToList().Where(e => e.IsActive == true);
List<Employee> emp = employeeData.ToList();
//emp.FindLastIndex(e => e.)
employeeDto = Mapper.Map<List<Employee>,List<EmployeeDto>>(emp);
};
return employeeDto;
}
This is my GetLatestEmployeeByID code :
public int GetEmployeeLatestID(EmployeeDto employeeDto)
{
using (EmployeeDataEntities entities = new EmployeeDataEntities())
{
var employeeData = entities.Employees.ToList().Where(e => e.IsActive == true);
List<Employee> emp = employeeData.ToList();
emp.FindLastIndex(e => e.ID);
}
}
I have tried a couple of solutions and i end up with this one:
var a = new List<EmployeeDto>()
{
new EmployeeDto()
{
SerialNumber = 1,
ID = "AB01",
FirstName = "Ala",
MiddleName = "b",
LastName = "ala"
},
new EmployeeDto()
{
SerialNumber = 2,
ID = "AB02",
FirstName = "Ala",
MiddleName = "b",
LastName = "ala"
},new EmployeeDto()
{
SerialNumber = 3,
ID = "AB03",
FirstName = "Ala",
MiddleName = "b",
LastName = "ala"
}
};
// biggestIdAsInt = 230 a.max returns the max value after the calculations
var biggestIdAsInt = a.Max(employee => Encoding.ASCII.GetBytes(employee.ID) // get Employee Id as byte array
.Sum(b => b)); // summ the bytes for each employee
// 230
var substractedNumberFromBiggestId = Regex.Match(a.FirstOrDefault(x => x.ID.ToCharArray().Sum(y => y) == biggestIdAsInt).ID, #"\d+").Value;
Console.WriteLine(substractedNumberFromBiggestId);
I have put comments to make the code a little bit clearer.

How to fill object with list using EF

How can I fill a list field using EF and linq of this model
public class Infraccion
{
public int IdInfraccion { get; set; }
public string Serie { get; set; }
public int Numero { get; set; }
public Direccion Direccion { get; set; }
public string Comentario { get; set; }
public DateTime Fecha { get; set; }
public DateTime Hora { get; set; }
public string Dominio { get; set; }
public List<Contravencion> ListaDeContravenciones = new List<Contravencion>();
}
I DO know how to fill simple propertires, but dunno how to fill field List object where Contravencion is define like
public class Contravencion
{
public string Articulo { get; set; }
public string Inciso { get; set; }
public int IdContravencion { get; set; }
public string Descripcion { get; set; }
public int UfijasMinimo { get; set; }
public int UfijasMaximo { get; set; }
}
So far this is what I have
var listadoInfracciones = (from u in _context.Usuario
join ui in _context.UsuarioInfracciones on u.UsuarioId equals ui.UserId
join i in _context.Infraccion on ui.InfraccionId equals i.InfraccionId
join d in _context.Direcciones on i.IdDireccion equals d.DireccionId
where ui.UserId == usuario.IdUsuario
select new Infraccion
{
Comentario = i.Comentario,
Direccion = new Direccion
{
Calle = d.Calle,
Entre1 = d.Interseccion1,
Entre2 = d.Interseccion2
},
Dominio = i.Dominio,
Fecha = i.Fecha,
Numero = i.Numero,
Serie = i.Serie,
ListaDeContravenciones = new List<Contravencion>()
}).ToList();
Where can't find the right way to fill the list of Contravenciones. Heres the DB model:
I've already seen these posts but do NOT fit my needs Easy way to fill object
How to get data from the database into objectlists fast (with entity framework)
Ok so i found a way to solve my problem. I'm pretty sure it's not the best way but i least have a result. If anyone can do this entirely with linq i certainly know would be helpful not just for me but for the entire comunity. Heres my code:
var listadoInfracciones = (from u in _context.Users
join ui in _context.User_Infraccion on u.UsuarioId equals ui.UserId
join i in _context.Infraccions on ui.InfraccionId equals i.InfraccionId
join d in _context.Direccions on i.IdDireccion equals d.DireccionId
where ui.UserId == usuario.IdUsuario
select new Infraccion
{
Comentario = i.Comentario,
Direccion = new Direccion
{
Calle = d.Calle,
Entre1 = d.Interseccion1,
Entre2 = d.Interseccion2
},
Dominio = i.Dominio,
Fecha = i.Fecha,
Numero = i.Numero,
Serie = i.Serie,
IdInfraccion = i.InfraccionId
}).ToList();
foreach (var inf in listadoInfracciones)
{
var test = (from contra in _context.Contravencions
where contra.Infraccion_Contravencion.Any(c => c.InfraccionId == inf.IdInfraccion)
select new Contravencion
{
Articulo = contra.Articulo,
Inciso = contra.Inciso,
UfijasMaximo = contra.UFijasMax,
UfijasMinimo = contra.UFijasMin,
Descripcion = contra.Descripcion,
IdContravencion = contra.ContravencionId
}).ToList();
inf.ListaDeContravenciones = test;
}
Cheers!

Linq SelectMany With Null Child

MenuSetup and AccessRules have a one to many relation as described below.
public class MenuSetup
{
public virtual int MenuId { get; set; }
public virtual string DisplayText { get; set; }
public virtual int MenuOrder { get; set; }
public virtual bool MenuStatus { get; set; }
public virtual bool HasKids { get; set; }
public virtual IList<MenuAccessRules> AccessRules { get; set; }
}
public class MenuAccessRules
{
public virtual int Id { get; set; }
public virtual Boolean CanCreate { get; set; }
public virtual Boolean CanUpdate { get; set; }
public virtual Boolean CanDelete { get; set; }
public virtual FamsRoles Roles { get; set; }
public virtual MenuSetup Menu { get; set; }
}
I want to project the result of the query below in a view model
var result = session.QueryOver<MenuSetup>()
.Where(p => p.MenuId == id)
.List();
var vs = result.SelectMany(x => x.AccessRules, (a, b) => new MenuDetailsViewModel
{
MenuId = a.MenuId,
DisplayText = a.DisplayText,
MenuOrder = a.MenuOrder,
HasKids = a.HasKids,
MenuStatus = a.MenuStatus,
AccessRuleLists = a.AccessRules.
Select(c => new AccessRulesList {
Id = b.Id,
MenuId = b.Menu.MenuId,
RoleId = b.Roles.RoleId,
CanCreate = b.CanCreate,
CanUpdate = b.CanUpdate,
CanDelete = b.CanDelete }).ToList()
}).SingleOrDefault();
When AccessRules has data, vs returns MenuDetailsViewModel, but when AccessRules is Empty vs returns null.
Please how do i craft my selectMany to return MenuDetailsViewModel irrespective of AccessRules data.
Thanks in advance for your help
Would something like this:
var vs = result.Select(x => new MenuDetailsViewModel
{
MenuId = x.MenuId,
DisplayText = x.DisplayText,
MenuOrder = x.MenuOrder,
HasKids = x.HasKids,
MenuStatus = x.MenuStatus,
AccessRuleLists = x.AccessRules == null ? null : x.AccessRules.
Select(c => new AccessRulesList
{
Id = c.Id,
MenuId = c.Menu.MenuId,
RoleId = c.Roles.RoleId,
CanCreate = c.CanCreate,
CanUpdate = c.CanUpdate,
CanDelete = c.CanDelete
}).ToList()
}).SingleOrDefault();
Check below code it may help
var vs = result.SkipWhile(a=> a.AccessRules==null).SelectMany(x => x.AccessRules, (a, b) => new MenuDetailsViewModel
{
MenuId = a.MenuId,
DisplayText = a.DisplayText,
MenuOrder = a.MenuOrder,
HasKids = a.HasKids,
MenuStatus = a.MenuStatus,
AccessRuleLists = a.AccessRules.
Select(c => new AccessRulesList {
Id = b.Id,
MenuId = b.Menu.MenuId,
RoleId = b.Roles.RoleId,
CanCreate = b.CanCreate,
CanUpdate = b.CanUpdate,
CanDelete = b.CanDelete }).ToList()
}).SingleOrDefault();

Categories

Resources