I have list of User and Department Like below:
public class Users
{
public int id { get; set; }
public string jobTitle { get; set; }
public int officeLocation { get; set; }
public string userPrincipalName { get; set; }
}
public class Departments
{
public int id { get; set; }
public string department { get; set; }
public string displayName { get; set; }
}
Here is my Json
"Departments": [
{
"department": "Azure",
"id": "1",
"displayName": "Thad"
},
{
"department": "Visual Studio",
"id": "2",
"displayName": "Scott Hansalman"
},
{
"department": "C#",
"id": "3",
"displayName": "Paul"
}
]
"Users": [
{
"jobTitle": "Senior Program manager ",
"officeLocation": "Redmond",
"userPrincipalName": "thad.teams.com",
"id": "1"
},
{
"jobTitle": ""Technical Lead,
"officeLocation": "Redmond",
"userPrincipalName": "scott.teams.com",
"id": "2"
},
{
"jobTitle": "Development Engineer II",
"officeLocation": "Canada",
"userPrincipalName": "paul.teams.com",
"id": "3"
}
]
I want to join two list using linq where I would pass id of user
and get department.
I tried like this
var query = from user in Users
join dept in Departments
on user.id equals dept.id
select new
{
user.id ,
user.jobTitle,
user.officeLocation,
dept.department
}.where(id = 1) ;
But where clause doesn't seems okay, say's where doesn't exits in current context
This will work, you're just missing some ( )s, and there is a syntax error in the where...
(from user in Users
join dept in Departments
on user.id equals dept.id
select new
{
user.id ,
user.jobTitle,
user.officeLocation,
dept.department
}).Where(c => c.id == 1) ;
But usually, the Where is done upfront, as query expression.
Related
I have two JSONs files Country & Ceremony
Country JSON:
[
{
"Short": "AF",
"Name": "Afghanistan"
},
{
"Short": "AN",
"Name": "Netherlands Antilles"
},
{
"Short": "AI",
"Name": "Anguilla"
},
{
"Short": "AL",
"Name": "Albania"
} ]
Ceremony JSON:
[
{
"CName": "Fitr",
"CStart": "2021-11-10T09:00:00",
"CEnd": "2021-11-14T09:00:00",
"Loc": {
"Info": "",
"Short": "AF"
}
},
{
"CName": "Azha",
"CStart": "2023-06-17T09:18:44",
"CEnd": "2023-06-18T09:18:44",
"Loc": {
"Info": "",
"Short": "AI"
}
},
{
"CName": "Azha",
"CStart": "2022-01-05T00:00:00",
"CEnd": "2022-01-05T23:59:59",
"Loc": {
"Info": "",
"Short": "AL"
}
},
{
"CName": "Fitr",
"CStart": "2022-01-05T00:00:00",
"CEnd": "2022-01-05T23:59:59",
"Loc": {
"Info": "",
"Short": "AN",
}
}
]
Country Model Class
public class Country
{
public string Short{ get; set; }
public string Name { get; set; }
}
Ceremony Model Class
public class Ceremony
{
public string CName { get; set; }
public DateTime CStart { get; set; }
public DateTime End { get; set; }
public Loc loc { get; set; }
}
Loc Model Class
public class Loc
{
public string Info { get; set; }
public string Short { get; set; }
}
I want to show Country (Name) with a connection to Ceremony, Loc, and Short, so that when I read the Ceremony data in front of Short, I can see the full name of the country. Country full name should come from Country JSON.
Results should be like this:
CName CStart CEnd Short Name
Fitr "" "" AF Afghanistan
Azha "" "" AI Anguilla
How can I use LINQ to display the top countries i.e., using (Short) with the most ceremonies in 2021?
You can join two entities on ShortName like below :
var countries = ...;
var ceremonies = ...;
var result = (from c in countries
join ce in ceremonies on c.Short equals ce.loc.Short
select new {
ce.CName,
ce.CStart,
ce.Cend,
c.Short,
c.Name
}).Where(r=> r.CStart.Year == 2021).
GroupBy(r=> r.Short).Select(r=> new { Short = r.Key,
EventCount = r.Count()}).OrderByDescending(r=> r.EventCount)
.ToArray();
Edit
Added grouping and sorting as the question evolves.
I am creating an API which call to get the data via the Entity Framework Core 6.
Basically, have the following classes:
For parent class, let's say I have the following.
public class Student
{
public string student_ID { get; set; }
public string Name { get; set; }
public string GradeID { get; set; }
public ICollection<Address> address { get; set; }
public ICollection<Grade> grade { get; set; }
}
And the first child class, I have the class name address, with the same student ID. So I will use Icollection to join these two classes (Student and Address).
public class Address
{
public string student_ID { get; set; }
public int Seq { get; set; }
public string Address { get; set; }
public Student student { get; set; }
}
For the Grade, Let's say I have an ID & SubjectID as a primary key, and I want to join the parent class with SubjectID (Where grade ID is not a primary key in the Student class). I tried with the following setup on the following class:
public class Subject
{
public int SubjectID{ get; set; }
public int GradeID{ get; set; }
public string Description { get; set; }
public Student student { get; set; }
}
How can I make the API result to JSON to be the following:
[
{
"student_ID": "001"
"Name": "Jason"
"GradeID": [
{
"SugjectID": "S01"
"GradeID": "Grade_6"
"Description": "English"
},
{
"student_ID": "001"
"GradeID": "Grade_6"
"Description": "Math"
}
],
"Address": [
{
"student_ID": "001"
"Seq": "1"
"Address": "123 Apple Street"
},
{
"SubjectID": "001"
"Seq": "2"
"Address": "123 Orange Road"
}
]
}
]
I tried to not doing any relationship mapping in between Student & Subject, by doing join in API with the following:
var result = dbcontext.studnet.Include(x => x.Address).where( x => x.student_ID == strStudentID).Join(dbcontext.Subject, x => x.Student_ID, y => y.Student_ID, (x, y) => new {x, y});
return OK(result);
But it give me the following result which is duplicate:
[
{
"student_ID": "001"
"Name": "Jason"
"GradeID": [
{
"SugjectID": "S01"
"GradeID": "Grade_6"
"Description": "English"
},
{
"student_ID": "001"
"GradeID": "Grade_6"
"Description": "Math"
}
],
"Address": [
{
"student_ID": "001"
"Seq": "1"
"Address": "123 Apple Street"
}
]
},
{
"student_ID": "001"
"Name": "Jason"
"GradeID": [
{
"SugjectID": "S01"
"GradeID": "Grade_6"
"Description": "English"
},
{
"student_ID": "001"
"GradeID": "Grade_6"
"Description": "Math"
}
],
"Address": [
{
"SubjectID": "001"
"Seq": "2"
"Address": "123 Orange Road"
}
]
}
]
I tried so many methods, but could not find a solution. What can I try next?
I have a problem with my C# code. I can't produce my JSON well.
I'm using NHIBERNATE to connect and select data from my SQL Server. I want to produce a JSON with a list object inside it. Need your help guys.
NHibernate code:
var query = (from partners in session.Query<Partners>()
join partnerUsers in session.Query<PartnerUsers>() on partners.PartnerId equals partnerUsers.PartnerId
where partners.PartnerId == partnerId
select new Partnersss
{
PartnerId = partners.PartnerId,
PartnerName = partners.Name,
PartnerUsers = new PartnerUsersss()
{
LoginId = partnerUsers.LoginId
}
}).ToList<object>();
return query;
Class:
public class PartnerUsersss
{
public int PartnerUserId { get; set; }
public string LoginId { get; set; }
}
public class Partnersss
{
public int PartnerId { get; set; }
public string PartnerName { get; set; }
public PartnerUsersss PartnerUsers { get; set; }
}
JSON result:
{
"Data": "",
"data": [{
"PartnerId": 1,
"PartnerName": "ExpressPay",
"PartnerUsers": {
"PartnerUserId": "0",
"LoginId": "a#a.com"
}
}, {
"PartnerId": 1,
"PartnerName": "ExpressPay",
"PartnerUsers": {
"PartnerUserId": "0",
"LoginId": "b#b.com"
}
}],
"ResponseCode": "0",
"ResponseMessage": "Successful"
}
But I want to be able to produce this JSON instead:
{
"Data": "",
"data": [{
"PartnerId ": 1,
"PartnerName": "ExpressPay ",
"PartnerUsers": [{
"partnerUserId": "0",
"loginId": "a#a.com"
}, {
"partnerUserId": "0",
"loginId": "b#b.com"
}]
}],
"ResponseCode": "0",
"ResponseMessage": "Successful"
}
I tried using List with this kind of code
PartnerUsers = new List<PartnerUsersss>
and also change the class. But I got an error
List does not contain a definition for LoginId
In new class:
public List<PartnerUsersss> PartnerUsers { get; set; }
You need to remove join from your query and modify your query like below,
var query = (from partners in session.Query<Partners>()
where partners.PartnerId == partnerId
let partnerUsers = (from pu in session.Query<PartnerUsers>()
where pu.PartnerId == partners.PartnerId
select pu).ToList()
select new Partnersss
{
PartnerId = partners.PartnerId,
PartnerName = partners.Name,
PartnerUsers = partnerUsers
}).ToList();
You need to change the type of PartnerUsers property to List,
public List<PartnerUsersss> PartnerUsers { get; set; }
Take the following example:
public class Team
{
public int Id { get; set; }
public string TeamName { get; set; }
public Members[] Members { get; set; }
}
public class Members
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
If I have a C# list of teams comprised of the following:
[
{
"Id" : 1,
"TeamName" : "A",
"Members": [
{
"Id": 1,
"FirstName": "Arthur",
"LastName": "Nudge"
},
{
"Id": 2,
"FirstName": "Ken",
"LastName": "Shabby"
}
]
},
{
"Id" : 2,
"TeamName" : "B",
"Members": [
{
"Id": 1,
"FirstName": "Spiny",
"LastName": "Norman"
},
{
"Id": 2,
"FirstName": "Raymond",
"LastName": "Luxury-Yacht"
}
]
}
]
How can I write a Linq query to giva a result of Members but also with the Team Id e.g.
{
"TeamId": 1,
"Id": 1,
"FirstName": "Arthur",
"LastName": "Nudge"
},
{
"TeamId": 1,
"Id": 2,
"FirstName": "Ken",
"LastName": "Shabby"
},
{
"TeamId": 2,
"Id": 1,
"FirstName": "Spiny",
"LastName": "Norman"
}
I can return a Member list from the Team list by using
Teams.SelectMany(t => t.Members).ToList(); but how do I also include the TeamId
Use SelectMany in this way:
var q = Teams
.SelectMany(t => t.Members
.Select(tm => new{ TeamId = t.Id, tm.Id, tm.FirstName, tm.LastName }));
You could use a custom LINQ query to combine this into a list of anonymous objects with the fields you need:
var list = (from team in Teams
from member in team.Members
select new
{
TeamId = team.Id,
member.Id,
member.FirstName,
member.LastName
}).ToList();
Use a combination of SelectMany and Select:
teams.SelectMany(team => team.Members.Select(member => new
{
TeamId = team.Id,
MemberId = member.Id,
member.FirstName,
member.LastName
})).ToList();
The inner Select will map each member and the teams Id to an anonymous type.
The outer SelectMany flattens the nested IEnumerable<...> into a single IEnumerable<...>
I have the following json structure that I am getting from an api:
{
"event_instance": [
{
"id": 55551244,
"event_id": 11112,
"name": "Brown Belt Karate Class",
"staff_members": [
{
"id": 12345,
"name": "John Smith"
}
],
"people": [
{
"id": 111,
"name": "Jane Doe"
},
{
"id": 222,
"name": "Josh Smith"
},
{
"id": 333,
"name": "Ben Johnson"
}
],
"visits": [
{
"id": 1234578,
"person_id": 111,
"state": "completed",
"status": "complete"
},
{
"id": 1239865,
"person_id": 222,
"state": "completed",
"status": "complete"
},
{
"id": 1239865,
"person_id": 333,
"state": "canceled",
"status": "cancel"
}
]
}
]
}
I am deserializing this into the following .net objects using JSON.NET:
[JsonObjectAttribute("event_instance")]
public class EventInstance
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("event_id")]
public int EventId { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
[JsonPropertyAttribute("staff_members")]
public List<StaffMember> StaffMembers { get; set; }
[JsonPropertyAttribute("visits")]
public List<Visit> Visits { get; set; }
[JsonPropertyAttribute("people")]
public List<Student> Students { get; set; }
}
[JsonObjectAttribute("staff_members")]
public class StaffMember
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
}
[JsonObjectAttribute("people")]
public class People
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
}
[JsonObjectAttribute("visits")]
public class Visits
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("person_id")]
public int PersonId { get; set; }
[JsonPropertyAttribute("state")]
public string State { get; set; }
[JsonPropertyAttribute("status")]
public string Status { get; set; }
}
I am using the following code to de-serialize:
var event = (EventInstance)JsonConvert.DeserializeObject(json, typeof(EventInstance));
The above works fine and gives me an accurate object representation of the above json structure. Now I am trying to query this event object to filter/project to a new structure that I can then serialize back to json and send down to the browser. I need to return a list of students for the event that are in a state of "completed" and a status of "complete". As you can see, the people array ties to the visits array (with id and person_id). I would like to produce the following simple output:
11112, Brown Belt Karate Class, John Smith, 111, Jane Doe
11112, Brown Belt Karate Class, John Smith, 222, Josh Smith
I have tried something like this:
var studentList = from theClass in event
from staff in theClass.StaffMembers
from student in theClass.People
from visits in theClass.Visits
where visits.Status == "complete"
&& visits.State == "completed"
select new
{
event_id = theClass.EventId
class_name = theClass.Name,
instructor_name = staff.Name,
student_id = student.Id,
student_name = student.Name
};
string _data = JsonConvert.SerializeObject(studentList);
Naturally this produces duplicate student names. I am new to linq. Basically I need to join/tie the people and visits array so I just get back a single student for that id, along with the root data for this event. Any advice on a better way to do this is much appreciated too!
The trick is to join the students and visits into a collection that contains data of both:
from ei in eventInstances
from sm in ei.StaffMembers
from x in
(from vi in ei.Visits
join st in ei.Students on vi.PersonId equals st.Id
select new { vi, st }) // Here you get students and visits side-by-side
select new
{
ei.EventId,
Event = ei.Name,
StaffMemeber = sm.Name,
PersonId = x.st.Id,
Student = x.st.Name
}