LINQ how to order on a referenced List - linq

I have an object as defined like this
public class Person {
public Person() {
this.NewsItems = new List<NewsItem>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age {get;set;}
public virtual IList<NewsItem> NewsItems { get; set; }
}
The NewsItem object has a property called DisplayOrder and it is of type int. I then have LINQ as following:
return _repo.GetAll<Person>().Where(p => p.age >60).ToList();
My objective is have a sorted List<Person> based on DisplayOrder.
I am going to use this List<Person> in controller. In this controller I do have access to Person.NewsItems. I need to have List<Person> to be sorted in order or DisplayOrder which is inside the referenced list NewsItems.
Basically I have 1:m relationship between Person and NewsItem.

You can implement a custom comparer that you can use with .OrderBy. This could be against the NewsItems property. So you can do something like:
var sortedPersons = persons
.Where(p => p.Age > 60)
.OrderBy(x => x.NewsItems, new NewsItemsComparer());
Where your NewsItemComparer could take the form of:
public class NewsItemsComparer : IComparer<IList<NewsItem>>
{
public int Compare(IList<NewsItem> x, IList<NewsItem> y)
{
if (<logic where xDisplayOrders takes precedence over yDisplay Orders>)
{
return 1;
}
if (<logic where yDisplayOrders takes precedence over xDisplay Orders>)
{
return -1;
}
else
return 0;
}
}
Here's a sample implementation in which Persons are sorted according to which NewsItems has the lowest DisplayOrder number: https://dotnetfiddle.net/MTtwHU

Related

Fluent LINQ EF Core - Select filtered child property

I have the classes below:
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class ParentEntity
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
public ICollection<ChildEntity> ChildEntities { get; set; }
}
public class ChildEntity
{
public Guid Id { get; set; }
public int Vote { get; set; }
public Guid UserId { get; set; }
}
public class ReturnedParentDto
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
public int Vote { get; set; }
}
I want to be able to return a full list of ParenEntities, but take an Id of the User class (UserClassId), then filter the ParentEntity's ICollection where UserUid = UserClassId, so only 1 ChildEntity is always returned. Then I would want to extract a specific field from that returned ChildEntity and merge it with the ParentEntity fields. The end result should be like the ReturnedParentDto.
I want to do it in the style like
ParentEntities.Include(v => v.ChildEntities).ToList()
That seems to be possible in EF Core 5, but my project is in 3.1.
You can do this as below
Approach 1:
var result = result = parentEntities.Include(x => x.ChildEntities.Where(y => y.UserId == userId))
.Select(x => new ReturnedParentDto {
Id = x.Id,
SomeProperty = x.SomeProperty,
Vote = x.ChildEntities.FirstOrDefault()?.Vote // userId is the variable here
});
Approach 2:
var result = parentEntities.Select(x =>
new ReturnedParentDto {
Id = x.Id,
SomeProperty = x.SomeProperty,
Vote = x.ChildEntities.FirstOrDefault(y => y.UserId == userId)?.Vote // userId is the variable here
});

Applying expression functions

I need to implement filter function with expression parameter.
So i can't apply filtered query to entity.
Entity :
[XmlRoot(ElementName = "Zip")]
public class Zip
{
[XmlAttribute(AttributeName = "code")]
public string Code { get; set; }
}
[XmlRoot(ElementName = "District")]
public class District
{
[XmlElement(ElementName = "Zip")]
public List<Zip> Zip { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}
[XmlRoot(ElementName = "City")]
public class City
{
[XmlElement(ElementName = "District")]
public List<District> District { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "code")]
public string Code { get; set; }
}
[XmlRoot(ElementName = "AddressInfo")]
public class AddressInfo
{
[XmlElement(ElementName = "City")]
public List<City> City { get; set; }
}
Test case filtered by City name "Berlin". How can apply predicate with function.
public IConverter<T> Filter(Expression<Func<T, bool>> predicate)
{
// ???
return this;
}
I presume you need to filter a collection with a given predicate.
You can define a Filter extension method that takes a predicate as an argument (or simply rely on the already existing collection.Where extension method)
public static class Extensions
{
public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
return collection.Where(predicate);
}
}
define predicates based on your needs
// Filter by city Berlin
Func<City, bool> berlin = city => city.Name == "Berlin";
// Filter by district Spandau
Func<City, bool> spandau = city => city.Districts.Any(d => d.Name == "Spandau");
// Filter by zip 10115
Func<City, bool> zipcode = city =>
{
var predicate = from district in city.Districts
from zip in district.Zips
where zip.Code == "10115"
select zip;
return predicate.Any();
};
filter the data based on given predicate
var query = from address in addresses
from city in address.Cities.Filter(berlin)
select city;

Present multiple IEnumberables and single value properties in single webgrid

I have an Inventory Class that contains not only its own fields but several reference IDs to other classes.
public class Inventory {
public int Id { get; set; }
public string RtNum { get; set; }
public string AcntNum { get; set; }
public string CardNum { get; set; }
public string Num { get; set; }
[Range(1,3)]
public int Type { get; set; }
public int CompanyId { get; set; }
public int BranchId { get; set; }
public int PersonId { get; set; } }
In my action I generate several IEnumerable lists of the relevant fields from the other classes. I also have several non-list values I want to pass to the View. I know how to create a ViewModel to pass everything to the webgrid but have no way of iterating through the lists. I also know how to AutoMap an index to one list, see How to display row number in MVC WebGrid.
How would you combine the two so that you could use the index to iterate through multiple lists?
Update #1 (more detail)
public class Company {
public int Id { get; set; }
public string Name { get; set; } }
public class Branch {
public int Id { get; set; }
public string Name { get; set; } }
public class Person {
public int Id { get; set; }
public string Name { get; set; } }
public class MyViewModel {
public int PageNumber { get; set; }
public int TotalRows { get; set; }
public int PageSize { get; set; }
public IEnumerable<Inventory> Inventories { get; set; }
public int Index { get; set; }
public IEnumerable<string> CmpNm { get; set; }
public IEnumerable<string> BrnNm { get; set; }
public IEnumerable<string> PrnNm { get; set; } }
Controller
public class InventoryController : Controller
{ // I have a paged gird who’s code is not relevant to this discussion but a pagenumber,
// pagesize and totalrows will be generated
private ProjectContext _db = new ProjectContext();
public ActionResult Index() {
IEnumerable<Inventory> inventories = _db.Inventories;
List<string> cmpNm = new List<string>; List<string> brnNm = new List<string>; List<string> prnNm = new List<string>;
foreach (var item in inventories) { string x1 = "";
Company cmps = _db. Company.SingleOrDefault(i => i.Id == item.CompanyId); if (cmps!= null)
{ x1 = cmps.Name; } cmpNm.Add(x1); x1 = "";
Branch brns = _db. Branch.SingleOrDefault(i => i.Id == item. Branch Id); if (brns!= null) { x1 = brns.Name; } brnNm.Add(x1); x1 = "";
Person pers = _db.Persons.SingleOrDefault(i => i.Id == item. PersonId);
if (pers!= null) { x1 = pers.Name; } prnNm.Add(x1);
// the MyViewModel now needs to populated with all its properties and generate an index
// something along the line of
new MyViewModel { PageNumber= pagenumber, PageSize= pagesize, TotalRows=Totalrows, Inventories = inventories; CmpNm=cmpNm, BrnNm=brnNm, PrnNm=prnNm}
View (How to create the Index is the problem)
#model.Project.ViewModels.MyViewModel
#{ var grid = new WebGrid(Model.Inventories, Model.TotalRows, rowsPerPage: Model.PageSize); }
#grid.GetHtml( columns: grid.Columns(
Grid.Column(“PrnNm”, header: "Person", format: #Model.PrnNm.ElementAt(Index))
Grid.Column(“BrnNm”, header: "Branch", format: #Model.BrnNm.ElementAt(Index))
Grid.Column(“CmpNm”, header: "Company", format: #Model.CmpNm.ElementAt(Index))
grid.Column("RtNum", header: "Route"),
grid.Column("AcntNum", header: "Account"),
grid.Column("CardNum", header: "Card")
… ) )
What the grid should look like is self-evident.
It's pretty unclear what is your goal. But no matter what it is I would recommend you to define a real view model reflecting the requirements of your view and containing only the information you are interested in seeing in this grid:
public class InventoryViewModel
{
public int Id { get; set; }
public string PersonName { get; set; }
public string BranchName { get; set; }
public string CompanyName { get; set; }
public string RouteNumber { get; set; }
public string AccountNumber { get; set; }
public string CardNumber { get; set; }
}
Now you could have the main view model:
public class MyViewModel
{
public int PageNumber { get; set; }
public int TotalRows { get; set; }
public IEnumerable<InventoryViewModel> Inventories { get; set; }
}
Alright, the view is now obvious:
#model MyViewModel
#{
var grid = new WebGrid(
Model.Inventories,
rowsPerPage: Model.PageSize
);
}
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Id", header: "Inventory id"),
grid.Column("PersonName", header: "Person"),
grid.Column("BranchName", header: "Branch"),
grid.Column("CompanyName", header: "Company"),
grid.Column("RouteNumber", header: "Route"),
grid.Column("AccountNumber", header: "Account"),
grid.Column("CardNumber", header: "Card")
)
)
Now all that's left is build this view model in your controller. Since I don't know what you are trying to achieve here, whether you need an inner join or a left outer join on those columns, I will take as an example here a left outer join:
public ActionResult Index()
{
var inventories =
from inventory in _db.Inventories
join person in _db.Persons on inventory.PersonId equals person.Id into outerPerson
join company in _db.Companies on inventory.CompanyId equals company.Id into outerCompany
join branch in _db.Branch on inventory.BranchId equals branch.Id into outerBranch
from p in outerPerson.DefaultIfEmpty()
from c in outerCompany.DefaultIfEmpty()
from b in outerBranch.DefaultIfEmpty()
select new InventoryViewModel
{
PersonName = (p == null) ? string.Empty : p.Name,
CompanyName = (c == null) ? string.Empty : c.Name,
BranchName = (b == null) ? string.Empty : b.Name,
Id = inventory.Id,
AccountNumber = inventory.AcntNum,
CardNumber = inventory.CardNum,
RouteNumber = inventory.RtNum
};
var model = new MyViewModel
{
PageSize = 5,
// TODO: paging
Inventories = inventories.ToList()
};
return View(model);
}
And that's pretty much it. Of course in this example I am leaving the pagination of the Inventories collection for you. It should be pretty trivial now to .Skip() and .Take() the number of records you need.
As you can see ASP.NET MVC is extremely simple. You define a view model to reflect the exact requirements of what you need to show in the view and then populate this view model in the controller. Most people avoid view models because they fail to populate them, probably due to lack of knowledge of the underlying data access technology they are using. As you can see in this example the difficulty doesn't lie in ASP.NET MVC at all. It lies in the LINQ query. But LINQ has strictly nothing to do with MVC. It is something that should be learned apart from MVC. When you are doing MVC always think in terms of view models and what information you need to present to the user. Don't think in terms of what you have in your database or wherever this information should come from.

LINQ and Entity Framework, get sum of related rows of a non mapped column

I want to get the sum of applicants that applied to a specific position, this should not be saved as a column.
My model is simple:
We have positions:
net developer
java developer
We have applicants:
Luis
John
etc
We have applicants per position
With this column or property I want to know how many people have applied to each position, depending on the status.
So in my mvc view I want to show something like:
Position Applied Accepted Rejected ... other status
.net developer 5 3 2
java developer 3 2 1
The real problem here is the linq query which I am not very expert.
EDIT: I think I needed to change where the linq query must be coded, I suppose it should be in the ApplicantPosition class instead of Position, I also changed the types of Position and Application to be ICollection.
Please see the modified code.
public class Position
{
public int id { get; set; }
[StringLength(20, MinimumLength=3)]
public string name { get; set; }
public int yearsExperienceRequired { get; set; }
}
public class Applicant
{
public int ApplicantId { get; set; }
[StringLength(20, MinimumLength = 3)]
public string name { get; set; }
public string telephone { get; set; }
public string skypeuser { get; set; }
public ApplicantImage photo { get; set; }
}
public class ApplicantPosition
{
public virtual ICollection<Position> appliedPositions { get; set; }
public virtual ICollection<Applicant> applicants { get; set; }
public DateTime appliedDate { get; set; }
public int StatusValue { get; set; }
public Status Status
{
get { return (Status)StatusValue; }
set { StatusValue = (int)value; }
}
[NotMapped]
public int numberOfApplicantsApplied
{
get
{
var query =
from ap in appliedPositions
select new
{
positionName = g.Key.name,
peopleApplied = g.Count(x => x.Status == Status.Applied),
};
return query.Count(); ---??
}
}
}
Use direct SQL with PIVOT operator. This is really not a case for Linq query.
You can paste this into LINQPad as C# Program and run.
public enum Status
{
Applied,
Accepted,
Rejected
}
public class Position
{
public int id { get; set; }
public string name { get; set; }
}
public class Applicant
{
public int ApplicantId { get; set; }
public string name { get; set; }
}
public class ApplicantPosition
{
public Position appliedPosition { get; set; }
public Applicant applicant { get; set; }
public DateTime appliedDate { get; set; }
public Status Status { get; set; }
}
void Main()
{
var p1 = new Position { id = 1, name = ".net developer" };
var p2 = new Position { id = 2, name = "java developer" };
var a1 = new Applicant { ApplicantId = 100, name = "Luis" };
var a2 = new Applicant { ApplicantId = 200, name = "John" };
var ap1 = new ApplicantPosition { appliedPosition = p1, applicant = a1, Status = Status.Applied };
var ap2 = new ApplicantPosition { appliedPosition = p1, applicant = a2, Status = Status.Accepted };
var ap3 = new ApplicantPosition { appliedPosition = p2, applicant = a2, Status = Status.Rejected };
var db = new[] { ap1, ap2, ap3};
var query =
from ap in db
group ap by ap.appliedPosition into g
select new
{
positionName = g.Key.name,
peopleApplied = g.Count(x => x.Status == Status.Applied),
peopleAccepted = g.Count(x => x.Status == Status.Accepted),
peopleRejected = g.Count(x => x.Status == Status.Rejected),
};
query.Dump();
}
The result will be:
positionName peopleApplied peopleAccepted peopleRejected
.net developer 1 1 0
java developer 0 0 1
According to my experiences you can use LinQ or Entity Framework just by mapping your tables in to a DBML to a Entity Framework Model file.
In other way Microsoft gives you a Dynamic LinQ class that you can use it.I think you map all your columns and user Dynamic LinQ class.Good luck

LINQ - Combine multiple lists to form a new list and align them by key?

I have two list of different columns, but each list have a common column with the same key, how do I combine them into a new list, i.e:
public class TradeBalanceBreak
{
public int CommID { get; set; }
public int CPFirmID { get; set; }
public double CreditDfferenceNotional { get; set; }
public string Currency { get; set; }
}
public class Commission
{
public int CommID { get; set; }
public PeriodStart { get; set; }
public ResearchCredit { get; set; }
}
public class CommissionList
{
public List<Commission> Commissions { get { return GetCommissions(); }}
private List<Commission> GetCommissions()
{
// retrieve data code ... ...
}
}
public class TradeBalanceBreakModel
{
public List<TradeBalanceBreak> TradeBalanceBreaks { get; set; }
}
public class CommissionModel
{
public List<CommissionList> CommissionLists { get; set; }
}
What I would like to achieve is to combine/flatten the TradeBalancesBreaks and CommissionLists (from the model classes) into one. The CommID is shared between the two.
Thanks.
Using Join (extension method version) -- after your update
var list1 = GetTradeBalanceBreaks();
var list2 = new CommisionsList().Commissions;
var combined = list1.Join( list2, l1 => l1.ID, l2 => l2.First().ID,
(l1,l2) = > new
{
l1.CommID,
l1.CPFirmID,
l1.CreditDifferenceNotional,
l1.Currency,
PeriodStarts= l2.SelectMany( l => l.PeriodStart ),
ResearchCredits = l2.SelectMany( l => l.ResearchCredit )
})
.ToList();
var combined = from p in PhoneNumbers
join a in Addresses on a.ID equals p.ID
select new {
ID = p.ID,
Name = p.Name,
Phone = p.Phone,
Address = a.Address,
Fax = a.Fax
};

Resources