I have:
var names = db.tblPosts.Select(x => new { x.UserID, x.title }).Distinct().ToList();
I want select UserID and title and UserID is distinct.
but not worked and userID is not distinct..
var items = db.tblPosts
.GroupBy(x => x.UserId)
.Select(g => new { UserId = g.Key, Title = g.FirstOrDefault().Title })
.ToList();
It will return first Title for each UserId. Add additional OrderBy/ThenBy to sort items within group before taking first one.
Related
For the given data set, I want to return the unique rows for each OrderId that has the lowest number for Status, so the result would be:
I have a working query that does that:
var result = _dbContext.Orders
.GroupBy(s => s.OrderId)
.Select(group => group.OrderBy(x => x.Status).First()).ToList();
However, I would like to modify this query to only return three selected fields for each table row, rather than the dozens that exist. I know I need to add something like this:
.Select(group => new
{
OrderId = ???,
Status = ???,
Date = ???
}
But I am unable to add this to my existing query and have it still work. How can I do this?
You can try to do something like this:
var result = _dbContext.Orders
.GroupBy(s => s.OrderId)
.Select(group => group.OrderBy(x => x.Status).First())
.Select(order => new
{
OrderId = order.OrderId,
Status = order.Status,
Date = order.Date
})
.ToList();
In SQL you'd use:
SELECT OrderID,MIN(Status) as Status
FROM Orders
GROUP BY OrderID
A LINQ query is similar:
var query = context.Orders
.GroupBy(o=>o.OrderId)
.Select(g=> new {
OrderId=g.Key.OrderId,
Status=g.Min(o=>o.Status)
});
var results=query.ToList();
I'm trying to make a linq using where, group by and select at same time but I cannot do it works and it always throws an exception.
How could I do it works ?
Linq
public ActionResult getParceiros(){
//return all partners
IList<ViewParceirosModel> lista = new List<ViewParceirosModel>();
lista = context.usuarios.Where(u => u.perfil == RoleType.Parceiro)
.Select(x => new ViewParceirosModel
{
id = x.id,
nomeParceiro = x.nome,
emailAcesso = x.email
})
.GroupBy(x => x.id)
.OrderBy(x => x.nomeParceiro)
.ToList();
return View(lista);
}
Exception
Your program doesn't do what you want. Alas you forgot to tell you what you want, you only showed us what you didn't want. We'll have to guess.
So you have a sequence of Usarios.
IQueryable<Usario> usarios = ...
I don't need to know what a Usario is, all I need to know is that it has certain properties.
Your first step is throwing away some Usarios using Where: you only want to keep thos usarios that have a Perfil equal to RoleType.Parceirdo:
// keep only the Usarios with the Perfil equal to RoleType.Parceirdo:
var result = usarios.Where(usario => usario.Perfil == RoleType.Parceirdo)
in words: from the sequence of Usarios keep only those Usarios that have a Perfil equal to RoleTyoe.Parceirdo.
The result is a subset of Usarios, it is a sequence of Usarios.
From every Usario in this result, you want to Select some properties and put them into one ViewParceirosModel:
var result = usarios.Where(usario => usario.Perfil == RoleType.Parceirdo)
.Select(usario => new ViewParceirosModel
{
Id = x.id,
NomeParceiro = x.nome,
EmailAcesso = x.email,
})
In words: from every Usario that was kept after your Where, take the Id, the Nome and the Email to make one new ViewParceirosModel.
The result is a sequence of ViewParceirosModels. If you add ToList(), you can assign the result to your variable lists.
However your GroupBy spoils the fun
I don't know what you planned to do, but your GroupBy, changes your sequence of ViewParceirosModels into a sequence of "groups of ViewParceirosModels" Every ViewParceirosModel in one group has the same Id, the value of this Id is in the Key.
So if after the GroupBy you have a group of ViewParceirosModel with a Key == 1, then you know that every ViewParceirosModel in this group will have an Id equal to 1.
Similarly all ViewParceirosModel in the group with Key 17, will have an Id equal to 17.
I think Id is your primary key, so there will only be one element in each group. Group 1 will have the one and only ViewParceirosModel with Id == 1, and Group 17 will have the one and only ViewParceirosModel with Id == 17.
If Id is unique, then GroupBy is useless.
After the GroupBy you want to Order your sequence of ViewParceirosModels in ascending NomeParceiro.
Requirement
I have a sequence of Usarios. I only want to keep those Usarios with a Perfil value equal to RoleType.Parceirdo. From the remaining Usarios, I want to use the values of properties Id / Nome / Email to make ViewParceirosModels. The remaining sequence of ViewParceirosModels should be ordered by NomeParceiro, and the result should be put in a List.
List<ViewParceirosModel> viewParceiroModels = Usarios
.Where(usario => usario.Perfil == RoleType.Parceirdo)
.Select(usario => new ViewParceirosModel
{
Id = x.id,
NomeParceiro = x.nome,
EmailAcesso = x.email,
}
.OrderBy(viewParceirosModel => viewParceirosModel.NomeParceiro)
.ToList();
When you create a LINQ query with group by clause, you receive as result a grouped query.
It is a kind of dictionary that has as key the field you chose to group and as value a list of records of this group.
So, you cannot order by "nomeParceiro" because this field is inside the group.
If you detail how you expect the result I can show you a code example for this.
You can find more details in this section of the doc: https://learn.microsoft.com/pt-br/dotnet/csharp/linq/group-query-results
Let's say ViewParceirosModel look like
public class ViewParceirosModel
{
public int id {get; set;}
public List<string> nomeParceiro {get; set;}
public List<string> emailAcesso {get; set;}
}
After that, you can Groupby then select combine with Orderby like below
IList<ViewParceirosModel> lista = new List<ViewParceirosModel>();
lista = context.usuarios.Where(u => u.perfil == RoleType.Parceiro)
.Select(x => new ViewParceirosModel
{
id = x.id,
nomeParceiro = x.nome,
emailAcesso = x.email
})
.GroupBy(x => x.id)
.Select(g => new ViewParceirosModel
{
id = g.Key,
nomeParceiro = g.Select(p => p.nomeParceiro).OrderBy(x => x.nomeParceiro).ToList()
nomeParceiro = g.Select(p => p.emailAcesso).ToList()
})
.ToList();
You can use the following code.
IList<ViewParceirosModel> lista = new List<ViewParceirosModel>();
lista = context.usuarios.Where(u => u.perfil == RoleType.Parceiro)
.Select(x => new ViewParceirosModel
{
id = x.id,
nomeParceiro = x.nome,
emailAcesso = x.email
})
.OrderBy(x => x.nomeParceiro)
.GroupBy(x => x.id)
.ToList();
or
List<List<ViewParceirosModel>> listb = context.usuarios
.Where(u => u.perfil == RoleType.Parceiro)
.GroupBy(g => g.id).OrderBy(g => g.Key)
.Select(g => g.OrderBy(x => x.nomeParceiro)).ToList();
I'm trying to select multiple columns not in a group by using linq - c#.
Using linq, I'm trying to group by ISNULL(fieldOne,''),ISNULL(fieldTo,'') and then select field_One, field_Two, field_Three for each group. So for each row that the group by would return, I want to see numerous rows.
So far I have the following, but can't seem to select all the needed columns.
var xy = tableQueryable.Where(
!string.IsNullOrEmpty(cust.field_One)
|| ! string.IsNullOrEmpty(ust.field_Two)
).GroupBy(cust=> new { field_One= cust.field_One ?? string.Empty, field_Tow = cust.field_Two ?? string.Empty}).Where(g=>g.Count()>1).AsQueryable();
Can somebody help pls?
You are pretty much there - all you are missing is a Select from the group:
var xy = tableQueryable
.Where(!string.IsNullOrEmpty(cust.first_name) || ! string.IsNullOrEmpty(ust.lastName))
.GroupBy(cust=> new { first_name = cust.first_name ?? string.Empty, last_name = cust.last_name ?? string.Empty})
.Where(g=>g.Count()>1)
.ToList() // Try to work around the cross-apply issue
.SelectMany(g => g.Select(cust => new {
Id = cust.Id
, cust.FirstName
, cust.LastName
, cust.RepId
}));
Select from each group does the projection of the fields that you want, while SelectMany dumps all the results into a flat list.
Would this work for you?
var groupsWithDuplicates = tableQueryable
.Where(c => !string.IsNullOrWhiteSpace(c.first_name) || !string.IsNullOrWhiteSpace(c.last_name))
.GroupBy(c => new { FirstName = c.first_name ?? "", LastName = c.last_name ?? "" })
.Where(group => group.Count() > 1) // Only keep groups with more than one item
.ToList();
var duplicates = groupsWithDuplicates
.SelectMany(g => g) // Flatten out groups into a single collection
.Select(c => new { c.first_name, c.last_name, c.customer_rep_id });
For me I have used following query to do the filter Customer and get the customer records group by the JobFunction. In my case the issue get resolved after adding the .AsEnumerable() after the where solve the problem.
var query = _context.Customer
.Where(x => x.JobTitle.ToUpper().Contains(searchText.ToUpper())).AsEnumerable()
.GroupBy(item => item.JobFunction,
(key, group) => new {
JobFunction = key,
CustomerRecords = group.ToList().Select(c => c).ToList()
})
.ToList();
I want to use distinct in linq. After i use disctinct i don't select any field. Is it possible to select after distinct.
query.select(x=>x.FirmName).Distinct().Select(x => new InvoiceSumReportrModel { Firma = x.FirmName, Id = x.Id,Country=x.Country }).AsQueryable();
Instead of using Distinct, you can use GroupBy to create a group for each FirmName, then grab the first firm from each group and project it to an InvoiceSumReportModel...
query.GroupBy(x => x.FirmName,
(k, g) => g.Select(
x => new InvoiceSumReportrModel
{
Firma = x.FirmName,
Id = x.Id,
Country = x.Country
})
.First());
Please help me convert this to a lambda expression
SELECT [UserID], MAX(Created) Created
FROM [UserHistory]
WHERE userid IN (14287)
GROUP BY [UserID]
Thanks!
EDIT:
Here's what I have so far.
List<T> list; //list is populated
table.Where(x => list.Select(y => y.ClientId).Contains( x.UserID))
.GroupBy(x => x.UserID)
.Select(x => new { x.UserID, x.Created })
.ToList();
When I add the GroupBy, my Select says there's no definition for x.UserID and x.Created.
Here you go:
var userIDs = new[] {14287, };
var results =
dataContext.UserHistories
.Where(user => userIDs.Contains(user.userID))
.GroupBy(user => user.userID)
.Select(
userGroup =>
new
{
UserID = userGroup.Key,
Created = userGroup.Max(user => user.Created),
});
Regarding your edit, as I said in comment, in .Select(x => new { x.UserID, x.Created }), x is no longer a UserHistory, it is IGrouping<int, UserHistory>(1), which does not have UserID and Created properties, but only Key property, which is an user id and implements IEnumerable to enumerate all items for the given key (user id).
Use #DaveShaw snippet as it is the most correct one and most efficient.
(1) I assume UserID is int.
var query = from history in context.UserHistories
where ( new[] {14287} ).Contains(history.userID)
group history by history.UserID into g
select new
{
UserId = g.Key,
MaxCreated = g.Max( x => x.Created)
};