Return additional column in Linq Query? - c#

I have this Linq query:
var area = db.MyDbSet
.Where(s => s.langid == langid)
.GroupBy(s => s.Title)
.Select(g => new { Title = g.Key })
.Select(s => s.Title);
I want to return another column from the same table, its called: CodeId.
I am noob Linq programmer and quite lost in all those mish-mash things in C# so I can't really understand what should I do.
Can somebody help me how to return the another column from the same table with the same query call?

This may help you :
var area = db.MyDbSet
.Where(s => s.langid == langid)
.GroupBy(s => s.Title)
.Select(g => new { Title = g.Key, CodeId = g.FirstOrDefault().CodeId });

var area = db.MyDbSet
.Where(s => s.langid == langid)
.GroupBy(s => s.Title)
.Select(g => new {
Title = g.Key,
CodeId = g.Id,
OtherField = "Field"
})

Related

How to convert a group_concat, join, and union query into linq lambda?

im pretty new to linq-lambda. I have a MySQL query that pulls the name of items in two tables union'd together. Then pull another column of the specialties that the items fall under.
my working query is this:
Select
p.title,
GROUP_CONCAT(spec.categoryname) genre
From
(SELECT FullName AS title, TypeId as typeid, Id as id FROM programs
UNION
SELECT FullName, TypeId, Id FROM products)
AS p
Inner join specialtymembers mem on (ItemType = p.typeid AND ItemId = p.id)
Inner join specialties spec on mem.Category = spec.id
GROUP BY p.title
ORDER BY p.title
now my problem is... that i have to somehow convert this into linq lambda. My attempt is this:
var allitems =
_programContentService.Products.Select(r => r.FullName)
.Union(_programContentService.Programs.Select(q => q.FullName))
.Join(_programContentService.SpecialtyMembers, z => z.ItemType, q => q.ItemType,
(z, q) => new {z, q})
.Join(_programContentService.Specialties, x => x.Id, z => z.Category,
(x, z) => new {x,z})
.Select(#t => new SelectListItem { Name = q.FillName.ToString(), Genre = "SOME HOW HAVE TO USE A LOOPING FEATURE??" });
UPDATE:
var allitems = _programContentService
.ProgramProductViews
.Select(x => new {x.FullName, x.TypeId, x.Id})
.Join(
_programContentService.SpecialtyMembers,
type => new {type.TypeId, type.Id},
member => new {TypeId = member.ItemType, Id = member.ItemId},
(type, member) => new {type.FullName, member.Category})
.Join(
_programContentService.Specialties,
q => q.Category,
specialty => specialty.Id,
(q, specialty) => new { q.FullName, specialty.SpecialtyName })
.GroupBy(x=>x.FullName)
.AsEnumerable()
.Select(x => new SelectListItem
{
Value = x.Key,
Text = String.Join(",", x.Select(q=>q.SpecialtyName))
});
i have a feeling that I am close...
I think this will get you what you want. It is untested, if you have issues let me know and I will work it out.
var allitems =
_programContentService
.Products
.Select(x => new { x.FullName, x.TypeId, x.Id })
.Union(
_programContentService
.Programs
.Select(x => new { x.FullName, x.TypeId, x.Id }))
.Join(
_programContentService.SpecialtyMembers,
type => new { type.TypeId, type.Id },
member => new { TypeId = member.ItemType, Id = member.ItemId },
(type, member) => new { type.FullName, member.Category })
.Join(
_programContentService.Specialties,
x => x.Category,
specialty => specialty.Id,
(x, specialty) => new { x.FullName, specialty.CategoryName })
.GroupBy(x => x.FullName)
.AsEnumerable()
.Select(x => new SelectListItem
{
Value = x.Key,
Text = String.Join(",", x.Select(y => y.CategoryName))
});

c# lambda reading each row with GROUP BY and SUM

This is the working query i was using in my management studio.
SELECT TOP 5 productCode, SUM(productSales) AS sales
FROM sellingLog
WHERE (salesYear = '2014')
GROUP BY productCode
ORDER BY sales DESC
I want to convert the query above into lambda, but i can't seems to make it works. the lambda still lacks of order by and select the productCode
var topProducts = sellingLog
.Where(s => s.salesYear == 2014)
.GroupBy(u => u.productCode)
.Select(b => b.Sum(u => u.productSales)).Take(5)
.ToList();
foreach(var v in topProduct)
{
//reading 'productCode' and 'sales' from each row
}
var topProducts = sellingLog
.Where(s => s.salesYear == 2014)
.GroupBy(u => u.productCode)
.Select(g => new { productCode = g.Key, sales = g.Sum(u => u.productSales) })
.OrderByDescending(x => x.productCode)
.Take(5)
.ToList();
You can use the .Key with group by to get productCode
var topProducts = sellingLog
.Where(s => s.salesYear == 2014)
.GroupBy(u => u.productCode)
.Select(b => new {u.Key, b.Sum(u => u.productSales)}).Take(5)
.OrderByDescending(b=>b.Sales)
.ToList();

How to find `Distinct` records in LINQ?

I want to find distinct records in entity framework. My code is as below
var distinctYear = _objCalRepos
.GetDetails()
.Select(o => new CalendarList { Mdate = o.Mdate.Year.ToString() })
.Distinct()
.ToList();
ddlYear.DataSource = distinctYear;
ddlYear.DataTextField = "Mdate";
ddlYear.DataValueField = "Mdate";
ddlYear.DataBind();
Here Distinct not works. It will return all entries(duplicated).
Distinct is not working, probably because CalendarList is not comparable.
Try this:
var distinctYear = _objCalRepos
.GetDetails()
.Select(o => o.Mdate.Year.ToString())
.Distinct()
.AsEnumerable()
.Select(o => new CalendarList { Mdate = o }))
.ToList();
You can use GroupBy
var distinctYear = _objCalRepos
.GetDetails()
.Select(o => new CalendarList { Mdate = o.Mdate.Year.ToString() })
.GroupBy(cl => cl.Mdate )
.Select(g => g.First())
.ToList();

Adding more parameters to a Linq query

I'm using this query to count number of orders by date. I'm trying to add one more parameter that counts total products for each order, however I can't get it to work atm.
This is the essential part of a method that is suposed to return a list of 3 parameters (Date, TotalOrders and TotalProducts). Im using a Linq query to get a list with total order for each date, im wondering how to add my third parameter to the list "TotalProducts" and if i can do by adding one more search parameter in the Query. The foreach part below do not work propertly, it will return a list of TotalProducts but CreationDate will be the same for ech item in the list. I also have a feeling putting a foreach inside a foreach dosn't seem optimal for this:
var orders = _orderService.SearchOrderStatistics(startDateValue, endDateValue, orderStatus,
paymentStatus, shippingStatus, model.CustomerEmail, model.OrderGuid);
var result = orders.Where(o => o.PaymentStatus == PaymentStatus.Paid)
.GroupBy(g => g.CreatedOnUtc.Date.ToString("yyyyMMdd"))
.Select(s => new { Date = s.Key, Count = s.Count() });
List<GCOrdersModel> TotalOrdersPaid = new List<GCOrdersModel>();
foreach (var g in result)
{
foreach (var opv in orders)
{
GCOrdersModel _Om = new GCOrdersModel(g.Date, g.Count.ToString(), opv.OrderProductVariants.Count.ToString());
TotalOrdersPaid.Add(_Om);
}
}
return TotalOrdersPaid;
To access total products for every orders I must use OrderProductVariants.Count.ToString()
Can I add this parameter to the query?
Thx
You could try this:
return orders.Where(o => o.PaymentStatus == PaymentStatus.Paid)
.GroupBy(g => g.CreatedOnUtc.Date.ToString("yyyyMMdd"))
.Select(s => new GCOrdersModel()
{
Date = s.Key,
Count = s.Count(),
OpvCount = opv.OrderProductVariants.Count.ToString()
})
.ToList();
or
return orders.Where(o => o.PaymentStatus == PaymentStatus.Paid)
.GroupBy(g => g.CreatedOnUtc.Date.ToString("yyyyMMdd"))
.Select(s => new GCOrdersModel(s.Key, s.Count, opv.OrderProductVariants.Count.ToString()))
.ToList();
That way, you don't have to iterate over your result again. And it automatically creates your list of GCOrdersModel.
Edit
Does this work?
return orders.Where(o => o.PaymentStatus == PaymentStatus.Paid)
.GroupBy(g => g.CreatedOnUtc.Date.ToString("yyyyMMdd"))
.Select(s => new GCOrdersModel()
{
Date = s.Key,
Count = s.Count(),
OpvCount = s.OrderProductVariants.Count.ToString()
})
.ToList();
or
return orders.Where(o => o.PaymentStatus == PaymentStatus.Paid)
.GroupBy(g => g.CreatedOnUtc.Date.ToString("yyyyMMdd"))
.Select(s => new GCOrdersModel(s.Key, s.Count(), s.OrderProductVariants.Count.ToString()))
.ToList();
How about:
var opvCount =
opv
.OrderProductVariants
.Count
.ToString();
return
orders
.Where(o => o.PaymentStatus == PaymentStatus.Paid)
.GroupBy(g => g.CreatedOnUtc.Date.ToString("yyyyMMdd"))
.Select(s => new
{
Date = s.Key,
Count = s.Count()
})
.Select(x =>
new GCOrdersModelg(x.Date, g.Count.ToString(), opvCount));

C# - LINQ to Entity query attaching the value of the properties to one variable

I have this query:
var sole = SoleService.All().Where(c => c.Status != 250)
.Select(x => new {
ID = x.ID, Code = new {CodeName = x.Code + x.Country},
Name = x.Name
})
.Distinct()
.OrderBy(s => s.Code);
Like this it gives me an error. What I want is to combine Code and Country like concat strings so I can use the new variable for my datasource. Something like - 001France
P.S
What I am using and is working right now is this :
var sole = SoleService.All().Where(c => c.Status != 250)
.Select(x => new {
ID = x.ID, Code = x.Code, Name = x.Name, Country = x.Country })
.Distinct()
.OrderBy(s => s.Code);
So what I need is to modify this query so I can use Code +Country as one variable. Above is just my try that I thought would work.
Sound like:
var sole = SoleService.All().Where(c => c.Status != 250)
.AsEnumerable()
.Select(x => new {
ID = x.ID,
Code = x.Code + x.Country,
Name = x.Name
})
.Distinct()
.OrderBy(s => s.Code);
You don't need inner anonymous type at all. If you are working on EF, sine string + is not supported, call AsEnumerable before doing select.
You can't sort by s.Code because it's an instance of an anonymous type. I'd go with
var sole = SoleService.All().Where(c => c.Status != 250)
.Select(x => new { ID = x.ID, Code = new {CodeName = x.Code + x.Country}, Name = x.Name })
.Distinct()
.OrderBy(s => s.Code.CodeName);
Try to add .toString() because the problem should be the + operator believe you try to add numeric properties...
Like that :
var sole = SoleService.All().Where(c => c.Status != 250)
.Select(x => new { ID = x.ID, Code = new {CodeName = x.Code.ToString() + x.Country.ToString()}, Name = x.Name })
.Distinct()
.OrderBy(s => s.Code);

Categories