I have a table:
DataTable store_temp = new DataTable();
store_temp.Columns.Add("patn");
store_temp.Columns.Add("rf");
store_temp.Columns.Add("name");
store_temp.Columns.Add("conv");
store_temp.Columns.Add("conv_type");
store_temp.Columns.Add("recorddate");
store_temp.Columns.Add("executiondate");
My C# code :
int i = 0;
var rowsgroups = (from row in store_temp.AsEnumerable().GroupBy(row =>
row.Field<string>("patn"))
.OrderBy((g => g.OrderByDescending(y => y.Field<string("executiondate")).ThenByDescending(y =>
y.Field<string>("rf"))))
select new
{
patn = row.ElementAt(i),
rf_num = ++i,
}).ToArray();
I want the lambda experession, which is equivalent to:
select patn, rf,
> row_number() over( partition by patn order by executiondate,rf )
as rf_num,
name, conv,conv_type, recorddate, executiondate
from store_temp2
But, lambda syntax ... var rowsgroups has just a one row..
I want to show all rows in store_temp.
What should I do to fix the query?
row_number() over(partition by patn order by executiondate, rf)
means in LINQ you need to group by patn, then order each group by executiondate, rf, then use the indexed Select overload to get row numbering inside the group, and finally flatten the result with SelectMany.
With that being said, the equivalent LINQ query could be something like this:
var result = store_temp.AsEnumerable()
.GroupBy(e => e.Field<string>("patn"), (key, elements) => elements
.OrderBy(e => e.Field<string>("executiondate"))
.ThenBy(e => e.Field<string>("rf"))
.Select((e, i) => new
{
patn = key,
rf = e.Field<string>("rf"),
rf_num = i + 1,
name = e.Field<string>("name"),
conv = e.Field<string>("conv"),
conv_type = e.Field<string>("conv_type"),
recorddate = e.Field<string>("recorddate"),
executiondate = e.Field<string>("executiondate")
}))
.SelectMany(elements => elements)
.ToArray();
Try something like this
select new
{
rowNum = store_temp.Rows.IndexOf(row),
patn = row.ElementAt(i),
rf_num = ++i,
}).ToArray();
I don't think you required any groupby as per your required sql
var i=0;
var rowsgroups = (from row in store_temp.AsEnumerable()
orderby row.Field<string>("executiondate") descending,
row.Field<string>("rf") descending
select new
{
patn = row.Field<string>("patn"),
rf_num = ++i,
name = row.Field<string>("name"),
conv = row.Field<string>("conv"),
conv_type = row.Field<string>("conv_type"),
recorddate = row.Field<string>("recorddate"),
executiondate = row.Field<string>("executiondate")
}).ToArray();
Related
I need to sum elements of same type starting from 2 LINQ queries.
Below is my code:
var query1 = from d in _contextProvider.Context.Documents
where d.TransportId == transportId
group d by d.Type
into dg
select new { DocumentType = dg.Key.ToString(), DocumentCount = dg.Count() };
var query2 = from n in _contextProvider.Context.NotificationDocuments
where n.TransportId == transportId
group n by n.TransportId
into nd
select new { DocumentType = "Notification", DocumentCount = nd.Count() };
var query_collapsed = query1.Union(query2)
.GroupBy(p => new { DocumentType = p.DocumentType })
.Select(g => new DocumentCounters() { DocumentType = g.Key.DocumentType, DocumentCount = g.Sum(p => p.DocumentCount) });
Example: below let's analyse values for DocumentType equals to Notification.
Values of query1:
Values of query2:
The collapsed query :
That's correct: 1 + 2 = 3
The problem: I noticed that whenever the count for Notification in query1 is equals to the count for Notification in query2, then the sum is not performed.
Example:
2 + 2 = 2
or
3 + 3 = 3
Any ideas ?
LINQ Union will remove duplicate entries. If you want to merge the two sequences you can use Concat like so:
var query_collapsed = query1.Concat(query2)
.GroupBy(p => new { DocumentType = p.DocumentType })
.Select(g => new DocumentCounters() { DocumentType = g.Key.DocumentType, DocumentCount = g.Sum(p => p.DocumentCount) });
I have a SQL query like this:
SELECT [Id],[WfInstanceId]
FROM [WfTask]
WHERE DocId IN
(SELECT [Id]
FROM [FormInstance]
WHERE FormId = '91889C15-7205-4467-B626-3C4AAB22567B')
How can I use it with linq? I want to return an IQueryable and pass it to my grid view.
var q = from row in WfTast
where (from x in FormInstance
where FormId='91889C15-7205-4467-B626-3C4AAB22567B' &&
row.DocId = id
select x).Any()
select Id, WfInstanceId;
Or, with join:
var q = from Task in WfTast
join Form in (FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B')
on Task.DocId = Form.Id
select Task.Id, Task.WfInstanceId;
or, Only flunet syntax:
var q = WfTast.Where(wt => FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B' &&
wt.DocId = x.id).Any());
or:
var formsIdCollection = FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B').Select(x => x.id);
// if you reuse this list, add at end this: .ToArray();
var q = from row in WfTast
where formsIdCollection.Contains(row.DocId)
select Id, WfInstanceId;
var query = DatabaseContext.WfTask.Where(
i => DatabaseContext.FormInstane
.Where(fi => fi.FormId = '...')
.Select(fi => fi.Id)
.Contains(i.DocId));
I spend a few hours trying to translate simple SQL to lambda LINQ
SELECT ID, AVG(Score) FROM myTable
GROUP BY ID
Any idea?
from t in myTable
group t by new {
t.ID
} into g
select new {
Average = g.Average(p => p.Score),
g.Key.ID
}
or Lambda
myTable.GroupBy(t => new {ID = t.ID})
.Select (g => new {
Average = g.Average (p => p.Score),
ID = g.Key.ID
})
The equivalent in Linq-to-Objects would be something like the below.
var results = from row in myTable
group row by row.Id into rows
select new
{
Id = rows.Key,
AverageScore = rows.Average(row => row.Score)
};
It's only slightly different for an ORM like entity framework. Namely, you would need to go through the data context or an appropriate DbSet/ObjectSet.
var _result = from a in myTable
group a by a.ID into g
select new
{
ID = g.Key.ID,
AverageResult = g.Average(x => x.Score)
}
I have a long list with ships that I get from a Linq to SQL query, but I only want one row per ImoNo. Today i have about 4 rows per ImoNo. I just need the one row that has been last updated (so in this example I need 2013-01-27).
This is my Linq To SQL query:
var res = from positions in context.Lloyds_ETAs
join vessels in context.Lloyds_Vessels on positions.ImoNumber equals vessels.imo_no
select new PositionData {
ImoNo = positions.ImoNumber,
PositionCordinates = positions.AIS_Latest_Position,
CompassOverGround = positions.Compass_over_Ground_Heading,
VesselId = positions.Vessel_ID,
Equipment = vessels.vessel_type,
Updated = positions.Last_Place_Location
};
return res.ToList();
var res = (from positions in context.Lloyds_ETAs
join vessels in context.Lloyds_Vessels on positions.ImoNumber equals vessels.imo_no
select new PositionData {
ImoNo = positions.ImoNumber,
PositionCordinates = positions.AIS_Latest_Position,
CompassOverGround = positions.Compass_over_Ground_Heading,
VesselId = positions.Vessel_ID,
Equipment = vessels.vessel_type,
Updated = positions.Last_Place_Location
})
.GroupBy(x => x.ImoNo)
.Select(g => g.OrderByDescending(pd => pd.Updated).First());
If you want the last one, all you have to do is append .OrderBy(pd => pd.Updated).Last() after your select.
var res = (from positions in context.Lloyds_ETAs
join vessels in context.Lloyds_Vessels on positions.ImoNumber equals vessels.imo_no
select new PositionData {
ImoNo = positions.ImoNumber,
PositionCordinates = positions.AIS_Latest_Position,
CompassOverGround = positions.Compass_over_Ground_Heading,
VesselId = positions.Vessel_ID,
Equipment = vessels.vessel_type,
Updated = positions.Last_Place_Location
}).OrderBy(pd => pd.Updated).Last();
return res.ToList();
(yourQuery).OrderByDescending(pd=>pd.Updated).First()
There are several ways to get just one "row" as a result:
res.OrderByDescending(x => x.Updated).Take(1);
res.OrderByDescending(x => x.Updated).First();
res.Order(x => x.Updated).Last();
It seems that you have some duplication though, so maybe doing a group by would be more appropriate.
i have table
id pagenane username
i want this sql query
select pagename, count(*) as num from pagestat where username='name' group by pagename
how can i do it by linq?
Well, try this:
var query = from row in context.pageStat
where row.UserName == "name"
group row by row.PageName into g
select new { PageName = g.Key, Count = g.Count() };
var retVal = (from s in dataContext.YourTable where
s.UserName.Equals("name")
group s by s.PageName into k
select new {PageName = k.Key, Count = k.Count() }).ToList();