What is a shortest way or LINQ query to remove non consecutive rows from list of grouped rows? - linq

Background: I am using Linq to get the data. Wrote below query to get List<List<InboxProcessingDto>> , now I want to remove record who don't have consecutive sequenceId in each List<InboxProcessingDto>.
List<InboxProcessingDto> will be always sorted.
Linq Query:
_context.Inboxes
.Join(_context.InboxProcessingOffsets, x => x.SequenceSource, y => y.Source, (x, y) => new InboxProcessingDto { Inbox = x, InboxProcessingOffset = y })
.Where(i => (i.Inbox.Status == InboxStatus.New ))
.Take(100)
.ToList()
.GroupBy(i => i.Inbox. SequenceSource)
.Select(grp => grp.OrderBy(i => i.Inbox.SequenceId))
.ToListAsync();
Above query gives me data like below screenshot:
List at [0] contains 4 objects of InboxProcessingDto and this dto has sequenceID, list[0] might have objects who don't have consecutive sequence id eg. 22, 23,27,28
from this list I want to remove 2 objects who has sequenceId 27,28
as we can see in screenshot next list from List<List> contains 5 objects of InboxProcessingDto and this dto has sequenceID, it might have objects who don't have consecutive sequence id eg. 2, 3,17,28,29
from this list I want to remove 3 objects who has sequenceId 17,28,29

Related

LINQ to Entities GroupBy, OrderByDescending, FirstOrDefault when

I have a following problem with LINQ to Entities. I am selecting records from DB, group them and then order them by Id descending. Then i want to select First item but only if Quantity is != 0. I think because i have to use FirstOrDefault i am getting wrong results but am not sure how to correct it.
DB
Now this query will give me ID's 2 and 1 grouped and 4 "grouped". What i need is to select FIRST items only if Quantity is != 0 and am not sure how to get that.
data = DbContext.Items.Where(x.WarehouseId == 1)
.GroupBy(x => x.ItemCode, (key, g) => g.OrderByDescending(y => y.Id).FirstOrDefault())
.OrderBy(parameters.SortExpression)
.Skip(parameters.Start)
.Take(parameters.Length);
If WarehouseID is 1 i need to get only row with ID 4 back. Any help is appreciated.
Edit: First i need to groupBy ItemCode, then i will have two groups for my case above. That's 1 and 2 for first group, and 4 for second group. Then i order them by Id descending and i get (2, 1), (4). Then i need to select first from group but only if Quantity is != 0. If Quantity is zero i don't want to select anything from a group.
Image to clarify what i need. I'm stuck on last step Take FristFrom each group only if quantity is != 0
EDIT: This is, what you want to do:
var data = DbContext.Items
.Where(p => p.WarehouseId == 1)
.GroupBy(p => p.ItemCode, (key, items) => new { Key = key, Items = items, ItemsCountWithQuantityZero = items.Where(p => p.Quantity == 0).Count() })
.Where(p => p.ItemsCountWithQuantityZero == 0)
.Select(p => p.Items.OrderByDescending(q => q.Id).First());

Get list of entities by list of id's - IN ORDER

See this question/answer: Entity Framework: Get all rows from the table for the ids in list
Now my question: I would like to get the entities sorted as they are in the list of id's.
I would be dealing with a small list, and don't mind if it's sorted in memory after pulling list from db.
var result = db.table
.Where(l => ids.Any(id => id == l.id))
.ToList()
.OrderBy(l => ids.IndexOf(l.id));
or
var result = db.table
.Where(l => ids.Contains(l.id))
.ToList()
.OrderBy(l => ids.IndexOf(l.id));
both should work fine.

Linq orderby and distinct

I have a table set up as follows:
Section SectionOrder
Sect1 1
Sect2 2
Sect3 3
Sect3 3
Sect1 1
Sect2 2
I need to pull out distinct sections in correct section order. Here is the linq that I'm using, but it's not putting them in the correct order for some reason.
var myVar = (from x in context.Documents
orderby x.SectionOrder ascending
select x.Section).Distinct();
I then want to be able to loop through myVar and put each item in a list as follows:
foreach (var t in myVar)
{
listOfDocTypeSections.Add(t);
}
The ordering of OrderBy and Distinct matters: while OrderBy produced an ordered sequence, Distinct doesn't. You need to put Distinct first, and then use OrderBy. However, since you take Distinct on one attribute, and order on the other attribute, you need to do it differently:
var myVar = context
.Documents
.GroupBy(x => x => x.Section) // This replaces Distinct()
.OrderBy(g => g.FirstOrDefault().SectionOrder) // There will be no default
.Select(g => g.Key);
This approach replaces Distinct with GroupBy, and orders on the first SectionOrder item of a group. You can change this sorting strategy to sort on some other item within the Section, say, Min or Max value of SectionOrder:
var myVar = context
.Documents
.GroupBy(x => x => x.Section)
.OrderBy(g => g.Max(x => x.SectionOrder))
.Select(g => g.Key);

ASP.NET MVC - Return a List, grouped by a property in my Model

How do I return a List, grouped by a property?
In my action, I return a view like so:
return View(context.Lines.Where(x=>x.EnquiryId == id).ToList());
This works fine, but what I need to do is group these Lines by a particular vehicle. In my Lines table, this has a column which stores the vehicle ID that a particular Line is linked too. For example, line 1 and 2, may have a vehicle ID of 1, where as line 3 and 4 may have a vehicle ID of 2.
Do you want to group or just order? Because if your result is a list of items, you'll just want to order them properly.
var result = context.Lines
.Where(x => x.EnquiryId == id)
.OrderBy(x => x.VehicleId)
.ToList();
GroupBy returns a list of lists:
var result = context.Lines
.Where(x => x.EnquiryId == id)
.GroupBy(x => x.VehicleId);

Find the max value in a grouped list using Linq

I have a linq expression that returns transactions in groups. Each transaction has a numerical value and I now need to know what is the highest value from all the transactions returned. This value is held in a field called TransactionId
Here is the expression I am using to get the grouped list.
var transactions = ctx.MyTransactions
.Where (x => x.AdapterId == Id)
.GroupBy(x => x.DeviceTypeId);
I now need to write an expression that works on the “transactions” grouped list to find the “max” of the TransactionId field. I’ve tried different ideas but none seem to work with the grouped results. I’m new to linq so I’m not sure how to do this.
Have you tried finding the maximum in each group and then finding the maximum of that over all groups?
int max = transactions.Max(g => g.Max(t => t.TransactionId));
Or you could just query the database again:
int max = ctx.MyTransactions
.Where(x => x.AdapterId == Id)
.Max(t => t.TransactionId);
This will give you the max in each group
var transactionIds = ctx.MyTransactions
.Where (x => x.AdapterId == Id)
.GroupBy(x => x.DeviceTypeId,
g => new {
DeviceTypeId = g.Key,
MaxTransaction = g.Max(x => x.TransactionId)
});

Resources