Reputation: 482
I have 2 list of objects
List<Student> studentList = new List<Student>() {
new Student(){ StudentName="Bill", MobileOS = "Android"},
new Student(){ StudentName="Bill", MobileOS = "Android"}
new Student(){ StudentName="Steve",MobileOS = "IOS"},
new Student(){ StudentName="Ram", MobileOS = "IOS"},
new Student(){ StudentName="Bill", MobileOS = "IOS"}
}
In my other list, I want to store filtered data. Example
List<FilteredData> filteredData= new List<FilteredData>(){
new FilteredData(){ StudentName="Bill", Count=3, Android = 2, Ios = 1},
new FilteredData(){ StudentName="Steve",Count=1, Android = 0, Ios = 1},
new FilteredData(){ StudentName="Ram", Count=1, Android = 0, Ios = 1},
}
Noted: the Count value is based on the occurrence of same StudentName and the number of Android and Ios is based on MobileOS
So, how can I count the same Student name and store it into a new list? I searched whole day but seems can't found a solution for this
Upvotes: 0
Views: 117
Reputation: 9482
var filtereddata = studentList
.GroupBy(x => x.SudentID)
.Select(x => new FilteredData() {
StudentID = x.Key,
StudentName = x.First().StudentName,
Count = x.Count(),
Android = x.Count(y => y.MobileOS == "Android"),
Ios = x.Count(y => y.MobileOS == "IOS")
});
Upvotes: 1
Reputation: 46
Using linq you could reduce it to
var filteredData =
studentList
.GroupBy(item => item.StudentName)
.Select(group => new FilteredData
{
StudentID = group.First().StudentID,
StudentName = group.Key,
Count = group.Count()
})
.ToList();
Upvotes: 2