Nested LINQ query selection - c#

Please consider following example class construct:
public class Company
{
public string CompanyName { get; set; }
public List<Subdivision> Subdivisions { get; set; }
}
public class Subdivision
{
public string SubdivisionName { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
}
Example variable of a List:
List<Company> CompanyList = new List<Company>();
CompanyList.Add(new Company
{
CompanyName = "TestCompany",
Subdivisions = new List<Subdivision>
{
{ new Subdivision
{
SubdivisionName = "TestSubdivision",
Employees = new List<Employee>
{
{ new Employee
{
EmployeeID = 1,
EmployeeName = "John"
}
}
}
}}
}
});
I want to get the EmployeeName just by EmployeeID. Consider this code:
if (CompanyList.Any(x => x.Subdivisions.Any(y => y.Employees.Any(z => z.EmployeeID == 1))))
{
int i1 = CompanyList.IndexOf(CompanyList.Where(x => x.Subdivisions.Any(y => y.Employees.Any(z => z.EmployeeID == 1))).Select(x => x).First());
int i2 = CompanyList[i1].Subdivisions.IndexOf(CompanyList[i1].Subdivisions.Where(x => x.Employees.Any(z => z.EmployeeID == 1)).Select(x => x).First());
int i3 = CompanyList[i1].Subdivisions[i2].Employees.IndexOf(CompanyList[i1].Subdivisions[i2].Employees.Where(z => z.EmployeeID == 1).Select(x => x).First());
string i = CompanyList[i1].Subdivisions[i2].Employees[i3].EmployeeName;
Console.WriteLine(i);
}
else
{
Console.WriteLine("Employee with ID 1 not found!");
}
This works just fine; however, it seems rather bloated up if I just want to retrieve a piece of data without getting the indexes. Is there any other approach to this?

You can use SelectMany to search for all employees in all divisions in all companies and then use FirstOrDefault to make sure null would be returned if no employee would be found
var employee = CompanyList.SelectMany(company => company.Subdivisions.SelectMany(division => division.Employees))
.FirstOrDefault(emp => emp.EmployeeID == 1);
if (employee != null)
{
Console.WriteLine(employee.EmployeeName); //prints John
}
else
{
Console.WriteLine("Employee with ID 1 not found!");
}

Related

To find the best Projects depending on the Project Likes, Project Connected and Project Rating

I have this table:
PL_ProjectLikes
PC_ProjectConnect
PR_ProjectRating
P_Project
PL_PageLayout
This is my link query:
List<PProject> p = ctx.PProject.Where(x => x.PCountryCode == cC && x.PParentalGuidence == r).ToList();
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
Now PL_PageLayout has a field called PL_P_Id or PlPId, this is a guid.
What i want is to take theses tables figure out a rating or sum or count to pull the best projects to be filtered at the top of the list.
What i have done to extract each of these tables by grouping them with the PIdG which is a guid and is liked to each of the tables from the project and each project is a PL_PageLayout.
Extracted values from the tables:
PL_ProjectLIke:
var plike = ctx.PlProjectLike.Where(x => x.PlValue == "Like").Select(c => c).GroupBy(g => new { g.PlPIdG }, (key, group) => new { sumR = group.Count(), pidG = key.PlPIdG });
List<string> p0p = plike.Select(t => t.pidG).ToList();
PR_ProjectRating:
var prating = ctx.PrProjectRating.Where(x => x.PrIsDeleted == false).Select(k => k).GroupBy(g => new { g.PrPIdG }, (key, group) => new { sumR = group.Sum(k => k.PrValue), pidG = key.PrPIdG });
List<string> p0 = prating.Select(t => t.pidG).ToList();
PC_ProjectConnect:
var pconnect = ctx.PcProjectConnect.Where(x => x.PcStatus == "Connected").Select(c => c).GroupBy(g => new { g.PcPIdG }, (key, group) => new { sumR = group.Count(), pidG = key.PcPIdG });
List<string> p0pp = pconnect.Select(t => t.pidG).ToList();
How do i combine these filters above to find the best projects or pagelayouts using linq?
I tried this:
pppp = pppp.OrderBy(c => p0.Contains(c.PlPId) ? p0.IndexOf(c.PlPId) : int.MaxValue).ToList();
Which works and gets the best projects by the sum of the ratings for each project, but how do i combine the other two querys to find the best project?
Would this be the answer or would this just get the query of the last set:
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
pppp = pppp.OrderBy(c => p0.Contains(c.PlPId) ? p0.IndexOf(c.PlPId) : int.MaxValue).ToList();
pppp = pppp.OrderBy(c => p0p.Contains(c.PlPId) ? p0p.IndexOf(c.PlPId) : int.MaxValue).ToList();
pppp = pppp.OrderBy(c => p0pp.Contains(c.PlPId) ? p0p.IndexOf(c.PlPId) : int.MaxValue).ToList();
Every time im liking a project as im testing its pushing the project down the list so that bit of code above is not working but making some progress
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
pppp = pppp.OrderBy(c => p0.Contains(c.PlPId) ? p0.IndexOf(c.PlPId) : int.MaxValue).ToList();
pppp = pppp.OrderBy(c => p0p.Contains(c.PlPId) ? p0p.IndexOf(c.PlPId) : int.MaxValue).ToList();
pppp = pppp.OrderBy(c => p0pp.Contains(c.PlPId) ? **p0pp**.IndexOf(c.PlPId) : int.MaxValue).ToList();
I have put some test code together at RexTester but I am not sure of your question. I think you can just order the result lists as they are created, or am I just misunderstanding the question
public class PlProjectLike
{
public int PlId { get; set; }
public Guid PlPIdG { get; set; }
public int PlUId { get; set; }
public string PlValue { get; set; }
public DateTime PlCreatedDate { get; set; }
}
public class PcProjectConnect
{
public int PcId { get; set; }
public Guid PcPIdG { get; set; }
public int PcUId { get; set; }
public DateTime PcCreatedDate { get; set; }
public string PcStatus{ get; set; }
}
public class PrProjectRating
{
public int PrId { get; set; }
public int PrUId { get; set; }
public string PrText { get; set; }
public int PrValue { get; set; }
public Guid PrPIdG { get; set; }
public DateTime PrCreatedDate { get; set; }
public bool PrIsDeleted{ get; set; }
}
public class PProject
{
public int PId { get; set; }
public Guid PIdG { get; set; }
public string PName { get; set; }
public DateTime PDateCreated { get; set; }
public bool PDeleted { get; set; }
public int PUId { get; set; }
public int PTtId { get; set; }
public string PCountry { get; set; }
public string PCountryCode { get; set; }
public string PParentalGuidence { get; set; }
public string PConnectionType { get; set; }
}
public class PlPageLayout
{
public int PLId { get; set; }
public Guid PlPId { get; set; }
public string PLName { get; set; }
}
public class CTX
{
public List<PProject> PProject { get; set; }
public List<PlPageLayout> PlPageLayout { get; set; }
public List<PlProjectLike> PlProjectLike { get; set; }
public List<PrProjectRating> PrProjectRating { get; set; }
public List<PcProjectConnect> PcProjectConnect { get; set; }
public CTX()
{
PProject = new List<PProject>();
PlPageLayout = new List<PlPageLayout>();
PlProjectLike = new List<PlProjectLike>();
PrProjectRating = new List<PrProjectRating>();
PcProjectConnect = new List<PcProjectConnect>();
}
}
public class LikeGroup
{
public int sumR { get; set; }
public Guid pidG { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
CTX ctx = new CTX();
String r = "R";
string cC = "us";
// Select project for country and rating
List<PProject> p = ctx.PProject.Where(x => x.PCountryCode == cC && x.PParentalGuidence == r).ToList();
// List of PlPageLayouts where the PlPId is in the selected PProject list
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
// List of Count/PlPIdG from PlProjectLike where the PlValue is 'Like' Ordered by the count descending
List<LikeGroup> plike = ctx.PlProjectLike.Where(x => x.PlValue == "Like").Select(c => c).GroupBy(g => new { g.PlPIdG }, (key, group) => new LikeGroup() { sumR = group.Count(), pidG = key.PlPIdG }).OrderByDescending(dat => dat.sumR).ToList();
// List of Sum(PrValue)/PlPIdG from PrProjectRating where PrIsDeleted is false Ordered by the Sum(PrValue) descending
List<LikeGroup> prating = ctx.PrProjectRating.Where(x => x.PrIsDeleted == false).Select(k => k).GroupBy(g => new { g.PrPIdG }, (key, group) => new LikeGroup(){ sumR = group.Sum(k => k.PrValue), pidG = key.PrPIdG }).OrderByDescending(dat => dat.sumR).ToList();
// List of Count/PlPIdG from PcProjectConnect where PcStatus is Connected Ordered by the count descending
List<LikeGroup> pconnect = ctx.PcProjectConnect.Where(x => x.PcStatus == "Connected").Select(c => c).GroupBy(g => new { g.PcPIdG }, (key, group) => new LikeGroup() { sumR = group.Count(), pidG = key.PcPIdG }).OrderByDescending(dat => dat.sumR).ToList();
List<PlProjectLike> OrderedProjectLikeList =
(from pl in ctx.PlProjectLike
join ord in plike on pl.PlPIdG equals ord.pidG
orderby ord.sumR descending
select pl).ToList();
List<PrProjectRating> OrderedPrProjectRatingList =
(from pr in ctx.PrProjectRating
join ord in prating on pr.PrPIdG equals ord.pidG
orderby ord.sumR descending
select pr).ToList();
List<PcProjectConnect> OrderedPcProjectConnectList =
(from pc in ctx.PcProjectConnect
join ord in prating on pc.PcPIdG equals ord.pidG
orderby ord.sumR descending
select pc).ToList();
}
}
From the help of this answer:
https://stackoverflow.com/questions/65014531/summing-a-value-inside-of-a-anonymous-type
I added the following code to get the best projects:
var ratings =
from r1 in ctx.PrProjectRating
where r1.PrIsDeleted == false
group r1.PrValue by r1.PrPIdG into g
select new
{
Id = g.Key,
Sum = g.Sum(),
};
var likes =
from l in ctx.PlProjectLike
where l.PlValue == "Like"
group 1 by l.PlPIdG into g
select new
{
Id = g.Key,
Count = g.Count(),
};
var connects =
from c1 in ctx.PcProjectConnect
where c1.PcStatus == "Connected"
group 1 by c1.PcPIdG into g
select new
{
Id = g.Key,
Count = g.Count(),
};
var ids = ratings.Select(r => r.Id)
.Union(likes.Select(l => l.Id))
.Union(connects.Select(c => c.Id))
.ToHashSet();
var query =
from i in ids
join ra in ratings on i equals ra.Id into rs
from ra in rs.DefaultIfEmpty()
join l in likes on i equals l.Id into ls
from l in ls.DefaultIfEmpty()
join co in connects on i equals co.Id into cs
from co in cs.DefaultIfEmpty()
select new
{
Id = i,
Ratings = ra?.Sum ?? 0,
Likes = l?.Count ?? 0,
Connects = co?.Count ?? 0,
};
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
pppp = query.OrderByDescending(x => x.Ratings + x.Likes + x.Connects).SelectMany(j => pppp.Where(s => s.PlPId == j.Id)).ToList();

Mapping between models efficiently

I'm a bit new to asp.net core. In this query, it keeps on requerying the db on every node to map from OrgStructures to ToOrgStructureModel is there a way we can make this more efficient:
This is the area where it keeps on requerying the db: .Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentNodeId == org.NodeId).Count() > 0))
Whole query:
public virtual IList<OrgStructureModel> GetAll()
{
using (var db = _context)
{
var result = db.OrgStructures
.Where(e => e.FiscalYear == 19)
.Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentNodeId == org.NodeId).Count() > 0))
.ToList();
_session.SetObjectAsJson("OrgStructure", result);
return result;
}
}
ToOrgStructureModel:
public static OrgStructureModel ToOrgStructureModel(this OrgStructure org, bool hasChildren)
{
return new OrgStructureModel
{
NodeId = org.NodeId,
ParentNodeId = org.ParentNodeId,
Name = org.Name,
DepartmentCode = org.DepartmentCode,
Acronym = org.Acronym,
LegacyId = org.LegacyId,
hasChildren = hasChildren
};
}
OrgStructureModel:
public class OrgStructureModel
{
[ScaffoldColumn(false)]
public int? NodeId { get; set; }
[Required]
public string Name { get; set; }
public string Acronym { get; set; }
public string DepartmentCode { get; set; }
public int? ParentNodeId { get; set; }
public int? LegacyId { get; set; }
public int FiscalYear { get; set; }
public int DepartmentId { get; set; }
[ScaffoldColumn(false)]
public bool hasChildren { get; set; }
public OrgStructure ToEntity()
{
return new OrgStructure
{
NodeId = NodeId,
Name = Name,
Acronym = Acronym,
ParentNodeId = ParentNodeId,
DepartmentCode = DepartmentCode,
LegacyId = LegacyId,
FiscalYear = FiscalYear,
DepartmentId = DepartmentId
};
}
}
Avoid using custom methods when using Linq-to-sql.
Here's a working alternative that doesn't use ToOrgStructureModel method:
var result = db.OrgStructures
.Where(e => e.FiscalYear == 19)
.Select(org => new OrgStructureModel
{
NodeId = org.NodeId,
ParentNodeId = org.ParentNodeId,
Name = org.Name,
DepartmentCode = org.DepartmentCode,
Acronym = org.Acronym,
LegacyId = org.LegacyId,
// Notice using "Any" method instead of comparing count with 0
hasChildren = db.OrgStructures.Any(s => s.ParentNodeId == org.NodeId),
})
.ToList();
You are creating a lot of queries, essentially for every record that it will pull out it will query one more time for each of them to check for hasChildren.
Include the link to the child in your main model (if it's a collection make it a collection),
public class OrgStructureModel
{
...
public int? ChildId {get;set;}
public OrgStructureModel Child {get;set;}
}
And then you can create a check in the query
var result = db.OrgStructures
.Where(e => e.FiscalYear == 19 && e.ChildId != null)
.Select(org => org.ToOrgStructureModel())
.ToList();
Also read this blog post on projection.

Linq query for the Multi list in singe out put

i have table looks like below
ID | Reason | PrID
-----------------
1 abc null
2 dhe null
3 aerc 1
4 dwes 2
5 adfje 1
i have class
public class Reason
{
public int Id { get; set; }
public string Reson{ get; set; }
public List<SecondryReason> SecReason{ get; set; }
public int? PrimaryId { get; set; }
}
public class SecondryReason
{
public int Id { get; set; }
public string Reason { get; set; }
public int PrimaryReasonId { get; set; }
}
I want this to be displayed in hierarchy level
if the prid is Null need to treat this as the parent remaining all child
i am trying Linq and unable to achieve this
Suggest me how to do this in an easy way in linq
So: You have a list/enumerable of type , whereof the SecReason List property is null. Then, using linq you want a list, were the only the "root" reasons remain, but the Sub-reasons got put in the lists, but as type SecondaryReason?
If so, I found this way to do it (linq and foreach):
static IEnumerable<Reason> GetReasonsGrouped(List<Reason> reasons)
{
var result = reasons.Where(x => x.PrimaryId == null);
foreach (var item in result)
{
item.SecReason = reasons.Where(x => x.PrimaryId == item.Id)
.Select(x => new SecondryReason()
{ Id = x.Id,
ReasonName = x.ReasonName,
PrimaryReasonId = item.Id
})
.ToList();
}
return result;
}
Or just linq, but harder to read:
var result = reasons.Where(x => x.PrimaryId == null)
.Select(x =>
{
x.SecReason = reasons.Where(r => x.PrimaryId == x.Id)
.Select(r => new SecondryReason()
{
Id = r.Id,
ReasonName = x.ReasonName,
PrimaryReasonId = x.Id
})
.ToList();
return x;
});
Not sure if linq will be the best solution, here is my proposed changes and method to get an Hierarchy type:
public class Reason
{
public int Id { get; set; }
public string Reson { get; set; }
public List<Reason> SecReason { get; set; }
public int? PrimaryId { get; set; }
//Adds child to this reason object or any of its children/grandchildren/... identified by primaryId
public bool addChild(int primaryId, Reason newChildNode)
{
if (Id.Equals(primaryId))
{
addChild(newChildNode);
return true;
}
else
{
if (SecReason != null)
{
foreach (Reason child in SecReason)
{
if (child.addChild(primaryId, newChildNode))
return true;
}
}
}
return false;
}
public void addChild(Reason child)
{
if (SecReason == null) SecReason = new List<Reason>();
SecReason.Add(child);
}
}
private List<Reason> GetReasonsHierarchy(List<Reason> reasons)
{
List<Reason> reasonsHierarchy = new List<Reason>();
foreach (Reason r in reasons)
{
bool parentFound = false;
if (r.PrimaryId != null)
{
foreach (Reason parent in reasonsHierarchy)
{
parentFound = parent.addChild(r.PrimaryId.Value, r);
if (parentFound) break;
}
}
if (!parentFound) reasonsHierarchy.Add(r);
}
return reasonsHierarchy;
}

Applying a Linq to Entities join on my code

I have code that works, but I worked around a 'Join' in Linq to Entities, because I could not figure it out.
Could you please show me how to succesfully apply it to my code?
My desired result is a dictionary:
Dictionary<string, SelectedCorffData> dataSelectedForDeletion = new Dictionary<string, SelectedCorffData>();
The above mentioned class:
public class SelectedCorffData
{
public long CorffId { get; set; }
public string ReportNumber { get; set; }
public DateTime CorffSubmittedDateTime { get; set; }
}
Please note the 'intersectResult' I am looping through is just a string collection.
Here is my code:
DateTime dateToCompare = DateTime.Now.Date;
Dictionary<string, SelectedCorffData> dataSelectedForDeletion = new Dictionary<string, SelectedCorffData>();
foreach (var mafId in intersectResult)
{
var corffIdsPerMaf = context
.Mafs
.Where(m => m.MafId == mafId)
.Select(m => m.CorffId);
var corffIdForMaf = context
.Corffs
.Where(c => corffIdsPerMaf.Contains(c.Id))
.OrderByDescending(c => c.CorffSubmittedDateTime)
.Select(c => c.Id)
.First();
//Selected close-out forms, whose MAF's may be up for deletion, based on date.
var corffData = context
.Corffs
.Where(c => c.Id == corffIdForMaf && System.Data.Entity.DbFunctions.AddYears(c.CorffSubmittedDateTime, 1).Value > dateToCompare)
.Select(c => new SelectedCorffData () { CorffId = c.Id, ReportNumber = c.ReportNumber, CorffSubmittedDateTime = c.CorffSubmittedDateTime })
.FirstOrDefault();
if(corffData != null)
{
dataSelectedForDeletion.Add(mafId, corffData);
}
}
Please note: this is not just a simple join. If it can't be simplified, please tell me. Also please explain why.
The code below I don't think is exactly right but it is close to what you need. I simulated the database so I could get the syntax correct.
namespace System
{
namespace Data
{
namespace Entity
{
public class DbFunctions
{
public static Data AddYears(DateTime submittedTime, int i)
{
return new Data();
}
public class Data
{
public int Value { get; set; }
}
}
}
}
}
namespace ConsoleApplication23
{
class Program
{
static void Main(string[] args)
{
Context context = new Context();
int dateToCompare = DateTime.Now.Year;
var corffIdsPerMaf = context.Mafs.Select(m => new { id = m.CorffId, mafs = m}).ToList();
var corffIdForMaf = context.Corffs
.Where(c => System.Data.Entity.DbFunctions.AddYears(c.CorffSubmittedDateTime, 1).Value > dateToCompare)
.OrderByDescending(c => c.CorffSubmittedDateTime).Select(c => new { id = c.Id, corff = c}).ToList();
var intersectResult = from p in corffIdsPerMaf
join f in corffIdForMaf on p.id equals f.id
select new SelectedCorffData() { CorffId = p.id, ReportNumber = f.corff.ReportNumber, CorffSubmittedDateTime = f.corff.CorffSubmittedDateTime };
Dictionary<string, SelectedCorffData> dataSelectedForDeletion = intersectResult.GroupBy(x => x.ReportNumber, y => y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
public class Context
{
public List<cMafs> Mafs { get; set;}
public List<cCorffs> Corffs { get; set;}
}
public class cMafs
{
public int CorffId { get; set; }
}
public class cCorffs
{
public DateTime CorffSubmittedDateTime { get; set; }
public int Id { get; set; }
public string ReportNumber { get; set; }
}
public class Test
{
}
public class SelectedCorffData
{
public long CorffId { get; set; }
public string ReportNumber { get; set; }
public DateTime CorffSubmittedDateTime { get; set; }
}
}

How to use condition for all children in Entity Framework

I have these classes:
public class product
{
public int Id { get; set; }
public string Title { get; set; }
public Store Store { get; set; }
public ICollection<Color> Colors { get; set; }
}
public class Color
{
public int Id { get; set; }
public string Name { get; set; }
public product Product { get; set; }
}
public class Store
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public ICollection<product> Products { get; set; }
}
And I have this list :
List<Store> Stores = new List<Store>
{
new Store { Id = 1, Name = "Lilo", City = "Teh",
Products = new List<product>
{
new product
{ Id = 1, Title = "Asus",
Colors = new List<Color> {
new Color { Id = 1, Name = "Blue"},
new Color { Id = 2, Name = "Orange"}
}
},
new product
{ Id = 2, Title = "Dell",
Colors = new List<Color> {
new Color { Id = 1, Name = "Yellow"},
new Color { Id = 2, Name = "Orange"},
new Color { Id = 3, Name = "Red"}
}
}
}
},
new Store{Id=2,Name="filo",City="san",
Products=new List<product>
{
new product{Id=3,Title="Asus",
Colors=new List<Color>{
new Color{Id=1,Name="Blue"},
new Color{Id=2,Name="Orange"}
}
},
new product{Id=4,Title="Dell",
Colors=new List<Color>{
new Color{Id=1,Name="Yellow"},
new Color{Id=2,Name="Lime"},
new Color{Id=3,Name="Red"}
}
}
}
}
};
I want to select all stores where Name ="Lilo" and products names is "Dell " and Color="Blue". I want do this in Entity Framework, not Linq.
I use this code but it doesn't work :
var test = Stores.Where(s => s.Name = "lilo" && s.Products.Where(p => p.Title == "Dell").FirstOrDefault().Title == "Dell" && s.Products.Where(c => c.Colors.Where(ct => ct.Name == "Blue").FirstOrDefault().Name = "Blue")).ToList();
How can I do this ?
Do this By Method Syntax :
var stlist = Stores.Where(s => s.Name.ToLower() == "lilo" && s.Products.Where(p => p.Colors.Any(c=>c.Name=="Blue") && p.Title == "Dell").FirstOrDefault().Title == "Dell").ToList();
Updated :
And Hopeless's Answers is (best answers):
var lslist2= Stores.Where(s => s.Name == "lilo" && s.Products.Any(p => p.Title == "Dell" && p.Colors.Any(c => c.Color.Name == "Blue"))).ToList();
And by Linq :
var test = (from s in Stores
from p in s.Products
from c in p.Colors
where s.Name=="Lilo" && p.Title=="Dell"&& c.Name=="Blue"
select s
).ToList();

Categories