This is my code:
public class Photos
{
public long PhotoLabel { get; set; }
public int UserID { get; set; }
}
List<Photos> photolist = new List<Photos>();
var result1 = photolist.OrderByDescending(p => p.PhotoLabel).ThenBy(r => r.UserID).ToList();
If I display the contents now, this is what I get (First sorted in descending order of PhotoLabel and then sorted by UserID:
|------|---------------------|---------------------|
| Row | UserID | PhotoLabel |
|----------------------------|---------------------|
| 1 | 92 | 20180729181046 |
|----------------------------|---------------------|
| 2 | 92 | 20180729181041 |
|----------------------------|---------------------|
| 3 | 92 | 20180729181037 |
|----------------------------|---------------------|
| 4 | 88 | 20180729174415 |
|----------------------------|---------------------|
| 5 | 88 | 20180729174405 |
|----------------------------|---------------------|
| 6 | 04 | 20180729174358 |
|----------------------------|---------------------|
| 7 | 1 | 20170924183847 |
|----------------------------|---------------------|
| 8 | 1 | 20170921231422 |
|----------------------------|---------------------|
| 9 | 1 | 20170920194624 |
|----------------------------|---------------------|
| 10 | 32 | 20170820114728 |
|----------------------------|---------------------|
| 11 | 32 | 20170820114725 |
|----------------------------|---------------------|
| 12 | 32 | 20170820114421 |
|----------------------------|---------------------|
| 13 | 32 | 20170820114416 |
|----------------------------|---------------------|
| 14 | 1 | 20170225151023 |
|----------------------------|---------------------|
| 15 | 1 | 20170225151000 |
|----------------------------|---------------------|
| 16 | 1 | 20170225150957 |
|----------------------------|---------------------|
From the sorted table above, this is what I want to achieve:
Display groups of UserIDs and PhotoLabels where UserIDs appear 3 or more times in one group (eg: rows 4 and 5 where UserID=88 and row 6 where UserID=04 should be eliminated since the UserID=88 appears just twice in the group and UserID=04 appears only once in the group).
Display only the top most group of UserIDs and exclude any repeating UserIDs (eg: rows 7,8 and 9 displays the UserID=1 group. Don't display any other UserID=1 group such as rows 14,15 and 16. )
The expected result from query should be:
|------|---------------------|---------------------|
| Row | UserID | PhotoLabel |
|----------------------------|---------------------|
| 1 | 92 | 20180729181046 |
|----------------------------|---------------------|
| 2 | 92 | 20180729181041 |
|----------------------------|---------------------|
| 3 | 92 | 20180729181037 |
|----------------------------|---------------------|
| 7 | 1 | 20170924183847 |
|----------------------------|---------------------|
| 8 | 1 | 20170921231422 |
|----------------------------|---------------------|
| 9 | 1 | 20170920194624 |
|----------------------------|---------------------|
| 10 | 32 | 20170820114728 |
|----------------------------|---------------------|
| 11 | 32 | 20170820114725 |
|----------------------------|---------------------|
| 12 | 32 | 20170820114421 |
|----------------------------|---------------------|
| 13 | 32 | 20170820114416 |
|----------------------------|---------------------|
Thank you so much in in advance! :-)
If I am not misunderstood the requirement, below function properly works (but it shouldn't the most efficient solution)
protected List<AnObject> aFunction(List<AnObject> sortedList)
{
//Display groups of UserIDs and PhotoLabels where UserIDs appear 3 or more times in one group (eg: rows 4 and 5 where UserID = 88 and row 6 where UserID = 04 should be eliminated since the UserID = 88 appears just twice in the group and UserID = 04 appears only once in the group).
//Display only the top most group of UserIDs and exclude any repeating UserIDs(eg: rows 7, 8 and 9 displays the UserID = 1 group.Don't display any other UserID=1 group such as rows 14,15 and 16.
int pivot = -1;
int cnt = 0;
List<AnObject> masterList = new List<AnObject>();
List<AnObject> subList = new List<AnObject>();
//List<int> Excluded = new List<int>();
foreach (AnObject r in sortedList)
{
if (pivot != r.UserID)
{
if (cnt > 2)
{
masterList.AddRange(subList);
//Excluded.Add(pivot);
}
subList.Clear();
pivot = -1;
cnt = 0;
//if (!Excluded.Contains(r.UserID))
if (!masterList.Any(x => x.UserID == r.UserID))
{
pivot = r.UserID;
}
}
subList.Add(r);
cnt++;
}
return masterList;
}
To call it for testing
protected class AnObject
{
public AnObject(int uid, string photolabel)
{
this.UserID = uid;
this.PhotoLabel = photolabel;
}
public int UserID { get; set; }
public string PhotoLabel { get; set; }
}
protected void Execute()
{
List<AnObject> sortedList = new List<AnObject>();
sortedList.Add(new AnObject(92, "anystring"));
sortedList.Add(new AnObject(92, "anystring"));
sortedList.Add(new AnObject(92, "anystring"));
sortedList.Add(new AnObject(88, "anystring"));
sortedList.Add(new AnObject(88, "anystring"));
sortedList.Add(new AnObject(4, "anystring"));
sortedList.Add(new AnObject(1, "anystringfirst"));
sortedList.Add(new AnObject(1, "anystringfirst"));
sortedList.Add(new AnObject(1, "anystringfirst"));
sortedList.Add(new AnObject(32, "anystring"));
sortedList.Add(new AnObject(32, "anystring"));
sortedList.Add(new AnObject(32, "anystring"));
sortedList.Add(new AnObject(32, "anystring"));
sortedList.Add(new AnObject(1, "anystringafter"));
sortedList.Add(new AnObject(1, "anystringafter"));
sortedList.Add(new AnObject(1, "anystringafter"));
List<AnObject> bb = aFunction(sortedList);
}
Please wait! This is not the final answer! a little bit further modification is needed! modification is underway.
List<Photos> photolist = new List<Photos>()
{
new Photos() {UserID = 92, PhotoLabel = 20180729181046},
new Photos() {UserID = 92, PhotoLabel = 20180729181041},
new Photos() {UserID = 92, PhotoLabel = 20180729181037},
new Photos() {UserID = 88, PhotoLabel = 20180729174415},
new Photos() {UserID = 88, PhotoLabel = 20180729174405},
new Photos() {UserID = 04, PhotoLabel = 20180729174358},
new Photos() {UserID = 1, PhotoLabel = 20170924183847},
new Photos() {UserID = 1, PhotoLabel = 20170921231422},
new Photos() {UserID = 1, PhotoLabel = 20170920194624},
new Photos() {UserID = 32, PhotoLabel = 20170820114728},
new Photos() {UserID = 32, PhotoLabel = 20170820114725},
new Photos() {UserID = 32, PhotoLabel = 20170820114421},
new Photos() {UserID = 32, PhotoLabel = 20170820114416},
new Photos() {UserID = 1, PhotoLabel = 20170225151023},
new Photos() {UserID = 1, PhotoLabel = 20170225151000},
};
var photolist2 = photolist.GroupBy(g => g.UserID)
.Select(p => new
{
UserId = p.Key,
Count = p.Count()
})
.ToList();
var filteredPhotoList = photolist
.Join(photolist2,
photo => photo.UserID,
photo2 => photo2.UserId,
(photo, photo2) => new {UserId = photo.UserID, PhotoLabel =
photo.PhotoLabel, Count = photo2.Count})
.Where(p => p.Count > 2).Select(p => new
{
p.UserId, p.PhotoLabel
}).OrderByDescending(p => p.PhotoLabel).ThenBy(p => p.UserId).ToList();
Thank you all for your help. SKLTFZ's and TanvirArjel's answers were close but didn't achieve the expected results. I realized that you cannot achieve everything described above in Linq, so this is what I came up with and it achieves everything listed above:
PS: I renamed var result1 to ordered_photolist
List<Photos> ordered_photolist = photolist.OrderByDescending(p => p.PhotoLabel).ThenBy(r => r.UserID).ToList();
List<Photos> temp_photolist = new List<Photos>();
List<Photos> final_photolist = new List<Photos>();
int UserID = -1;
int UserIDCount = 0;
foreach (Photos p in ordered_photolist)
{
if (UserID == -1)
{
UserID = p.UserID;
temp_photolist.Add(p);
UserIDCount++;
}
else
{
if ( UserID == p.UserID )
{
temp_photolist.Add(p);
UserIDCount++;
}
else
{
if ( UserIDCount >= 3 )
{
// add temp_photolist to final list
int index = final_photolist.FindIndex(item => item.UserID == UserID);
if (index == -1)
{
// element does not exists, do what you need
final_photolist.AddRange(temp_photolist);
}
temp_photolist.Clear();
temp_photolist.Add(p);
UserIDCount = 1;
UserID = p.UserID;
}
else
{
temp_photolist.Clear();
UserIDCount = 0;
UserID = -1;
}
}
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to select fields from unique records within a table with multiple where clauses. I currently am using C# and LINQ fluent syntax connected with NHibernate. So I am wondering if there is a way to create this query that way. Here is a test dataset:
+----+----------+------+------+
| Id | ParentId | Name | Type |
+----+----------+------+------+
| 1 | 100 | A | 1 |
| 2 | 100 | A | 2 |
| 3 | 100 | A | 3 |
| 4 | 200 | B | 1 |
| 5 | 300 | A | 1 |
| 6 | 300 | A | 2 |
| 7 | 400 | A | 1 |
| 8 | 400 | A | 2 |
| 9 | 400 | A | 3 |
| 10 | 400 | A | 4 |
+----+----------+------+------+
I can get the results I want using this SQL query:
SELECT ParentId, COUNT(Name) as Cnt, Max(Id) as Id, Max(Name) as Name, Max(Type) as Type FROM TestGroupBy Where Name = 'A' Group By ParentId;
This gives the result:
+----------+-----+----+------+------+
| ParentId | Cnt | Id | Name | Type |
+----------+-----+----+------+------+
| 100 | 3 | 3 | A | 3 |
| 300 | 2 | 6 | A | 2 |
| 400 | 4 | 10 | A | 4 |
+----------+-----+----+------+------+
I know how to make the group by query but I can't figure out how to do the multiple MAX selects. Is that just not possible with LINQ? If it's not, then what would be a way that I could go about this?
Here's a small snippet that shows you the linq query in context:
public class Row
{
public int Id;
public int ParentId;
public string Name;
public int Type;
public Row(int Id, int ParentId, string Name, int Type)
{
this.Id = Id;
this.ParentId = ParentId;
this.Name = Name;
this.Type = Type;
}
}
class Program
{
static void Main(string[] args)
{
List<Row> test = new List<Row>();
test.Add(new Row(1, 100, "A", 1));
test.Add(new Row(2, 100, "A", 2));
test.Add(new Row(3, 100, "A", 3));
test.Add(new Row(4, 200, "B", 1));
test.Add(new Row(5, 300, "A", 1));
test.Add(new Row(6, 300, "A", 2));
test.Add(new Row(7, 400, "A", 1));
test.Add(new Row(8, 400, "A", 2));
test.Add(new Row(9, 400, "A", 3));
test.Add(new Row(10, 400, "A", 4));
dynamic d = from row in test
where row.Name.Equals("A")
group row by row.ParentId into grp
select new {
ParentId = grp.Key,
Cnt = grp.Count(),
Id = grp.Max(x => x.Id),
Name = grp.Max(x => x.Name),
Type = grp.Max(x => x.Type)
};
}
}
When you have a queryable, you can call Select and pass a predicate. The new keyword constructs an object with the schema you prefer.
.Select( x => new
{
ParentId = x.ParentId
Cnt = x.Count(p => p.Name),
Id = x.Max( p => p.Id )
/*etcetera*/
} );
I have a table where each JunctionlistID is repeated many times. there is a JunctionlistID in front of each id in each row.
I want to select entire row for each JunctionlistID where ID is latest. There are total 5 columns in this table i want all columns to get selected when i select that row.
ID | MonitoringString| JunctionListId | area_id| CompanyProfileId
1 | 1006410001D0 | 267 | 910064 | 7
2 | 1206420001D0 | 268 | 910065 | 7
3 | 1306440001D0 | 267 | 910064 | 7
4 | 1506450001D0 | 268 | 910065 | 7
5 | 1606470001D0 | 267 | 910064 | 7
6 | 1806480001D0 | 268 | 910065 | 7
7 | 1006420001D0 | 267 | 910064 | 7
8 | 1006470001D0 | 268 | 910065 | 7
9 | 1006490001D0 | 267 | 910064 | 7
10 | 1006430001D0 | 268 | 910065 | 7
11 | 1006460001D0 | 285 | 910066 | 8
12 | 1006438001D0 | 268 | 910067 | 8
The Answer should be
ID | MonitoringString| JunctionListId | area_id| CompanyProfileId
9 | 1006490001D0 | 267 | 910064 | 7
10 | 1006430001D0 | 268 | 910065 | 7
I try the query as below -
Select ID,MonitoringString,JunctionListId,area_id,CompanyProfileId from tblMonitoring where CompanyProfileId=7
I need the query same as well in linq and SQL both, If anybody know please give me the proper solution.
Thanks
If I understand correctly, you just want the last records for each company and junction id, based on the id. You can use row_number():
Select m.*
from (select m.*,
row_number() over (partition by CompanyProfileId, JunctionListId order by id desc) as seqnum
from tblMonitoring m
) m
where CompanyProfileId = 7 and seqnum = 1;
https://dotnetfiddle.net/oiRkzO
using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<Item> items = new List<Item>()
{
new Item() { ID = 1, MonitoringString = "1006410001D0", JunctionListId = 267, area_id = 910064 , CompanyProfileId = 7},
new Item() { ID = 2, MonitoringString = "1206420001D0", JunctionListId = 268, area_id = 910065 , CompanyProfileId = 7},
new Item() { ID = 3, MonitoringString = "1306440001D0", JunctionListId = 267, area_id = 910064 , CompanyProfileId = 7},
new Item() { ID = 4, MonitoringString = "1506450001D0", JunctionListId = 268, area_id = 910065 , CompanyProfileId = 7},
new Item() { ID = 5, MonitoringString = "1606470001D0", JunctionListId = 267, area_id = 910064 , CompanyProfileId = 7},
new Item() { ID = 6, MonitoringString = "1806480001D0", JunctionListId = 268, area_id = 910065 , CompanyProfileId = 7},
new Item() { ID = 7, MonitoringString = "1006420001D0", JunctionListId = 267, area_id = 910064 , CompanyProfileId = 7},
new Item() { ID = 8, MonitoringString = "1006470001D0", JunctionListId = 268, area_id = 910065 , CompanyProfileId = 7},
new Item() { ID = 9, MonitoringString = "1006490001D0", JunctionListId = 267, area_id = 910064 , CompanyProfileId = 7},
new Item() { ID = 10, MonitoringString = "1006430001D0", JunctionListId = 268, area_id = 910065 , CompanyProfileId = 7},
new Item() { ID = 11, MonitoringString = "1006460001D0", JunctionListId = 285, area_id = 910066 , CompanyProfileId = 8},
new Item() { ID = 12, MonitoringString = "1006438001D0", JunctionListId = 268, area_id = 910067 , CompanyProfileId = 8},
};
var result = items.GroupBy(item => item.JunctionListId).Select(g => g.FirstOrDefault(gx => gx.ID == g.Max(x => x.ID))).ToList();
var resultCmp7 = items.Where(item => item.CompanyProfileId == 7).GroupBy(item => item.JunctionListId).Select(g => g.FirstOrDefault(gx => gx.ID == g.Max(x => x.ID))).ToList();
foreach (var item in result)
{
Console.WriteLine(string.Format("{0},{1},{2},{3}",item.ID, item.MonitoringString, item.JunctionListId,item.area_id, item.CompanyProfileId));
}
Console.WriteLine();
foreach (var item in resultCmp7)
{
Console.WriteLine(string.Format("{0},{1},{2},{3}",item.ID, item.MonitoringString, item.JunctionListId,item.area_id, item.CompanyProfileId));
}
Console.ReadLine();
}
class Item
{
public int ID { get; set; }
public string MonitoringString { get; set; }
public int JunctionListId { get; set; }
public int area_id { get; set; }
public int CompanyProfileId { get; set; }
}
}
For linq, you could do the following. (Looks like you also want to filter by companyprofileid)
var result = items.Where(x=>x.CompanyProfileId==7)
.GroupBy(x=>x.JunctionListId)
.Select(x=>x.ToList()
.OrderByDescending(c=>c.ID)
.ThenBy(c=>c.JunctionListId)
.First());
Select MAX(ID) ID,
Max(MonitoringString) MonitoringString,
Max(JunctionListID) JunctionListID,
Max(area_id) area_id,
Max(CompanyProfileId) CompanyProfileId
from MonitorsList
where CompanyProfileId = 7
Group by JunctionListID
Try this one,
SELECT COUNT(ID), MonitoringString, JunctionListId, are_id, CompanyProfileId FROM tblMonitoring WHERE CompanyProfileID = '7' GROUP BY CompanyProfileId;
I am having issues with my nested foreach loop. I'm trying to populate data from by database to my list with information about car information (company, different car models). My issue has to do with my inner loop, and not being able to continue populating my list.
The results that I'm expecting is this:
"CompanyId": 1,
"CompanyName": "Toyota"
"ParentVehicleId": 2,
"ParentVehicleName": "Camry",
"ChildVehicleId": 4,
"ChildVehicleName":"Camry/Scepter"
"CompanyId": 1,
"CompanyName": "Toyota"
"ParentVehicleId": 4,
"ParentVehicleName": "Crown"
"ChildVehicleId": 0,
"ChildVehicleName":"N/A"
"CompanyId": 12,
"CompanyName": "Hyundai"
"ParentVehicleId": 13,
"ParentVehicleName": "Accent",
"ChildVehicleId": 0,
"ChildVehicleName":"N/A"
etc...
But what I'm actually getting is only these two:
"CompanyId": 1,
"CompanyName": "Toyota"
"ParentVehicleId": 2,
"ParentVehicleName": "Camry",
"ChildVehicleId": 3,
"ChildVehicleName":"Camry/Vista"
"CompanyId": 1,
"CompanyName": "Toyota"
"ParentVehicleId": 2,
"ParentVehicleName": "Camry",
"ChildVehicleId": 4,
"ChildVehicleName":"Camry/Scepter"
This is a snippet of my db table:
Vehicle Table
|----------------------------------------------|
| VehicleId | ManufactId | BrandName |
|----------------------------------------------|
| 1 | 1 | Toyota |
|----------------------------------------------|
| 2 | 1 | Camry |
|----------------------------------------------|
| 3 | 2 | Camry/Vista |
|----------------------------------------------|
| 4 | 2 | Camry/Scepter |
|----------------------------------------------|
| 5 | 4 | Crown |
|----------------------------------------------|
| 6 | 5 | Supra |
|----------------------------------------------|
C# code
public List<VehicleListModel>> VehicleMethod()
{
List<VehicleListModel> vehicleList = new List<VehicleListModel>();
foreach (var item in companyInfo)
{
var parentInfo = _context.VehicleTable.Where(y => item.VehicleId == y.ManufactId).ToList();
foreach (var item2 in parentInfo)
{
var childInfo = _context.VehicleTable.Where(y => item2.VehicleId == y.ManufactId).ToList();
foreach (var item3 in childInfo)
{
VehicleListModel vehList = new VehicleListModel();
//if ChildVehicleId does not exist, 0 & N/A are
//returned
vehList.CompanyId = item.VehicleId;
vehList.CompanyName = item?.BrandName ?? "N/A";
vehicleList.Add(vehList);
}
}
}
return vehicleList;
}
The problem is basically how your data is connected.
Let's take Toyota:
|----------------------------------------------|----------------|
| VehicleId | ManufactId | BrandId | BrandName |
|----------------------------------------------|----------------|
| 1 | null | 1 | Toyota |
|----------------------------------------------|----------------|
| 2 | 1 | 1 | Camry |
|----------------------------------------------|----------------|
| 3 | 2 | 1 | Camry/Vista |
|----------------------------------------------|----------------|
| 4 | 2 | 1 | Camry/Scepter |
As you can see, the model Camry is the relationship between the versions and the company.
When VehicleId is 2 (from Camry) you look for records where ManufactId is 2 (Vista and Scepter).
For Nissan instead:
|----------------------------------------------|----------------|
| VehicleId | ManufactId | BrandId | BrandName |
|----------------------------------------------|----------------|
| 9 | null | 9 | Nissan |
|----------------------------------------------|----------------|
| 10 | 9 | 9 | Datsun |
|----------------------------------------------|----------------|
| 11 | 9 | 9 | Datsun 13T |
Datsun doesn't have childs (no record have ManufactId equal to 10). Update Datsun 13 T record to ManufactId 10 to see it.
The same goes for the rest.
Moreover, because you hydrate the objects of the list inside the innermost foreach loop (and you never reach that code) you don't even get the empty objects.
If the data is wrong and you can't do anything about it, one possible way to handle these cases is to generate objects with the available info:
....
List<VehicleListModel> vehicleList = new List<VehicleListModel>();
var companies = _context.Where(x => x.ManufactId == null).ToList();
foreach (var company in companies)
{
var models = _context.Where(y => company.VehicleId == y.ManufactId).ToList();
if (models.Any())
{
foreach (var model in models)
{
var versions = _context.Where(y => model.VehicleId == y.ManufactId).ToList();
if (versions.Any())
{
foreach (var version in versions)
{
VehicleListModel vehList = new VehicleListModel();
vehList.CompanyId = company.VehicleId;
vehList.CompanyName = company?.BrandName ?? "N/A";
vehList.ParentVehicleId = model?.VehicleId ?? 0;
vehList.ParentVehicleName = model?.BrandName ?? "N/A";
vehList.ChildVehicleId = version?.VehicleId ?? 0;
vehList.ChildVehicleName = version?.BrandName ?? "N/A";
vehicleList.Add(vehList);
}
}
else
{
VehicleListModel vehList = new VehicleListModel();
vehList.CompanyId = company.VehicleId;
vehList.CompanyName = company.BrandName;
vehList.ParentVehicleId = model.VehicleId;
vehList.ParentVehicleName = model.BrandName;
vehList.ChildVehicleId = 0;
vehList.ChildVehicleName = "N/A";
vehicleList.Add(vehList);
}
}
}
else
{
VehicleListModel vehList = new VehicleListModel();
vehList.CompanyId = company.VehicleId;
vehList.CompanyName = company.BrandName;
vehList.ParentVehicleId = 0;
vehList.ParentVehicleName = "N/A";
vehList.ChildVehicleId = 0;
vehList.ChildVehicleName = "N/A";
vehicleList.Add(vehList);
}
}
....
Also, as #Yair suggested, you need to change Crown to ManufactId = 1
You are overriding the vehList instance in each iteration. Instead, you should move its initialization to the inner most loop, so a new instance is added to the list in each iteration:
foreach (var item in companyInfo)
{
var parentInfo = _context.VehicleTable.Where(y => item.VehicleId == y.ManufactId).ToList();
foreach (var item2 in parentInfo)
{
// This should be removed from the code:
// VehicleListModel vehList = new VehicleListModel();
var childInfo = _context.VehicleTable.Where(y => item2.VehicleId == y.ManufactId).ToList();
foreach (var item3 in childInfo)
{
// Instead, it's initialized here:
VehicleListModel vehList = new VehicleListModel();
//if ChildVehicleId does not exist, 0 & N/A are
//returned
vehList.CompanyId = item.VehicleId;
vehList.CompanyName = item?.BrandName ?? "N/A";
vehList.ParentVehicleId = item2?.VehicleId ?? 0;
vehList.ParentVehicleName = item2?.BrandName ?? "N/A";
vehList.ChildVehicleId = item3?.VehicleId ?? 0;
vehList.ChildVehicleName = item3?.BrandName ?? "N/A";
vehicleList.Add(vehList);
}
}
}
I have a problem with getting grouped columns in LINQ.
My class:
public class DTO_CAORAS
{
public int? iORAS_KEY_CON { get; set; }
public int? iMERC_KEY {get;set;}
public double? decD_ORAS_QUA {get;set;}
}
LINQ query:
var results =
from oras in listCAORAS_Delivered
group oras by new
{
oras.iORAS_KEY_CON,
oras.iMERC_KEY
}
into orasGroup
select new
{
decD_ORAS_QUA = orasGroup.Sum(x => x.decD_ORAS_QUA)
};
List results is filled only with one column - decD_ORAS_QUA. I don't know how to get columns, by which query is grouped - IORAS_KEY_CON and iMERC_KEY? I would like to fill results with iORAS_KEY_CON, iMERC_KEY and decD_ORAS_QUA.
Input data:
+---------------+-----------+---------------+
| iORAC_KEY_CON | iMERC_Key | decD_ORAS_QUA |
+---------------+-----------+---------------+
| 1 | 888 | 1 |
| 1 | 888 | 2 |
| 1 | 888 | 4 |
+---------------+-----------+---------------+
Desired output:
+---------------+-----------+---------------+
| iORAC_KEY_CON | iMERC_Key | decD_ORAS_QUA |
+---------------+-----------+---------------+
| 1 | 888 | 7 |
+---------------+-----------+---------------+
To also show the keys:
var results = from oras in listCAORAS_Delivered
group oras by new { oras.iORAS_KEY_CON, oras.iMERC_KEY } into g
select new DTO_CAORAS {
iORAS_KEY_CON = g.Key.iORAS_KEY_CON,
iMERC_KEY = g.Key.iMERC_KEY,
decD_ORAS_QUA = g.Sum(x => x.decD_ORAS_QUA)
};
As you are only grouping one column you can also:
var results = from oras in listCAORAS_Delivered
group oras.decD_ORAS_QUA by new { oras.iORAS_KEY_CON, oras.iMERC_KEY } into g
select new DTO_CAORAS {
iORAS_KEY_CON = g.Key.iORAS_KEY_CON,
iMERC_KEY = g.Key.iMERC_KEY,
decD_ORAS_QUA = g.Sum()
};
Hi I have a List below that needs to be grouped and aggregated using Linq method syntax.
| id |Code|Descr | Number | Expiry |
|---------|----|------|--------|-----------|
| guidId1 | A | Desc1| Number1| 2017-03-18|
| guidId2 | A | Desc1| Number1| 2017-03-18|
| guidId3 | B | Desc2| Number1| 2017-03-18|
| guidId4 | B | Desc2| Number1| 2017-03-18|
| guidId5 | C | Desc3| Number1| 2017-03-18|
| guidId6 | A | Desc1| Number2| 2020-05-20|
| guidId7 | A | Desc1| Number2| 2020-05-20|
| guidId8 | A | Desc1| Number2| 2020-05-20|
| guidId9 | B | Desc2| Number2| 2020-05-20|
| guidId10| C | Desc3| Number2| 2020-05-20|
| guidId11| C | Desc3| Number2| 2020-05-20|
I have tried this but am not sure how to include the count:
myList.GroupBy(s => new { s.Number, s.Code, s.Expiry});
The output I want from the list:
{Code = "A",Descr = "Desc1",Number = "Number1",Expiry = "2017-03-18", Count = 2}
{Code = "B",Descr = "Desc2",Number = "Number1",Expiry = "2017-03-18", Count = 2}
{Code = "C",Descr = "Desc3",Number = "Number1",Expiry = "2017-03-18", Count = 1}
{Code = "A",Descr = "Desc1",Number = "Number2",Expiry = "2020-05-20", Count = 3}
{Code = "B",Descr = "Desc2",Number = "Number2",Expiry = "2020-05-20", Count = 1}
{Code = "C",Descr = "Desc3",Number = "Number2",Expiry = "2020-05-20", Count = 2}
Thanks in advance
You've grouped the Number, Code, and Expiry, but your result needs the Descr as well. You need to include that in your group, then get the count of the groups.
var query =
from s in myList
group 1 by new { s.Code, s.Descr, s.Number, s.Expiry } into g
select new { g.Key.Code, g.Key.Descr, g.Key.Number, g.Key.Expiry, Count = g.Count() };