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);
Related
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());
I have a list of record that I picked up through the code:
var list= NhSession.QueryOver<Data.Models.MembModel>()
.Where(w => w.Comp.Id == idcomp)
.JoinQueryOver(jq => jq.Ver)
.Select(s => s.Ver)
.List<Dados.Models.VerModel>();
With this code I get a list of VerModel that I have relation in a MembModel. The problem is that I what get the list of VerModel that don't be in relation in a MembModal, I think to describe this, I want to select one list that is "notin" a first list. How can I do this?
Tks
What we need, as you said, is a NOT IN (subquery) statement. And NHibernate does have a clear way how to achieve that. First the subquery, which will return MembModel collection (filtered or not - as needed), represented by the VerModel.ID
var subquery = QueryOver.Of<Data.Models.MembModel>()
// we can still filter this sub-select ... or not
// .Where(w => w.Comp.Id == idcomp)
// what we need to be returned is the reference id, the VerModel.ID
.Select(m => m.Ver.ID);
And now we will query the VerModel itself, with the NOT IN (subquery) clause:
var list = session.QueryOver<Dados.Models.VerModel>()
.WithSubquery
.WhereProperty(v => v.ID) // the ID to match the prev selected one
.NotIn(subquery) // should NOT be IN
.List<Dados.Models.VerModel>();
Check:
16.8. Subqueries
Linq newbie here, struggling with my first GroupBy query.
I have a list of objects of type KeywordInstance which represents a keyword, and the ID of the database record to which the keyword was applied.
Keyword RecordID
macrophages 1
macrophages 2
cell cycle 3
map kinase 2
cell cycle 1
What I want is a collection of all keywords, with a list of the RecordIDs to which each keyword was applied.
Keyword RecordIDs
macrophages 1, 2
cell cycle 1, 3
map kinase 2
I tried using Linq to get it into a new object. I only managed to get the distinct keywords.
var keywords = allWords
.GroupBy(w => w.keyword)
.Select(g => new {keyword = g.Key});
The problem is that I can't seem to get the values of g in any way. g is of the type IGrouping<String, KeywordInstance> and by documentation, it only has the property Key, but not even the property Value. All the examples I have seen on the Internet for groupby just tell me to select g itself, but the result of
var keywords = allWords
.GroupBy(w => w.keyword)
.Select(g => new {keyword = g.Key, RecordIDs = g});
is not what I want.
Any try to get something out of g fails with the error message System.Linq.IGropuing<string, UserQuery.KeywordInstance> does not have a definition for [whatever I tried].
What am I doing wrong here?
I think you are close to you solution.
var keywords = allWords
.GroupBy(w => w.keyword)
.Select(g => new
{
keyword = g.Key,
RecordIDs = g.Select(c => c.ID)
});
Just Select the records you need.
The reason you are seeing the Keyword-column as well as the ID-column, is becuase it's part of g
var keywords = allWords.GroupBy(w => w.keyword);
foreach (var itm in keywords)
{
var list = itm.ToList();
//list returns all of the original properties/values objects from allwords.
//itm.key returns w.keyword
}
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)
});
HI there I am hoping for some help with a query I have.
I have this query
var group =
from r in CustomerItem
group r by r.StoreItemID into g
select new { StoreItemID = g.Key,
ItemCount = g.Count(),
ItemAmount = Customer.Sum(cr => cr.ItemAmount),
RedeemedAmount = Customer.Sum(x => x.RedeemedAmount)
};
I am returning my results to a list so I can bind it listbox.
I have a property called EntryType which is an int. There are 2 available numbers 1 or 2
Lets say I had 3 items that my query is working with
2 of them had the EntryType = 1 and the 3rd had EntryType2. The first records had a ItemAmount of 55.00 and the 3rd had a ItemAmount of 50.00
How can I group using something simlar to above but minus the ItemAmount of 50.00 from the grouped amount to return 60.00?
Any help would be great!!
It's not really clear what the question is - are you just trying to ignore all items with an entry type of 2? To put it another way, you only want to keep entries with an entry type of 1? If so, just add a where clause:
var group = from r in CustomerItem
where r.EntryType == 1
group r by r.StoreItemID into g
select new {
StoreItemID = g.Key, ItemCount = g.Count(),
ItemAmount = Customer.Sum(cr => cr.ItemAmount),
RedeemedAmount = Customer.Sum(x => x.RedeemedAmount)
};
Change ItemAmount = ... to:
ItemAmount =
g.Where(x => x.EntryType == 1).Sum(cr => cr.ItemAmount) -
g.Where(x => x.EntryType == 2).Sum(cr => cr.ItemAmount),
I changed Customer to g because this seems to be an error, but it's not clear to me from your question what you mean here, so maybe this change is not what you want.
A slightly more concise method is to use test the entry type in the sum and use the ternary operator to choose whether to add the positive or negative value:
ItemAmount = g.Sum(cr => cr.EntryType == 1 ? cr.ItemAmount : -cr.ItemAmount),
This gives the value of 60.00 as you required.