How can I use Sum() in Linq? - c#

How do I convert this statement into LINQ?
SELECT Sum(Balance) FROM account WHERE name='stocks' AND userid=290;

decimal sumLineTotal = (from od in account
where name == 'stocks' && userid == 290
select Balance).Sum();

var sum = db.account.Where(a => a.name == "stocks" && a.userid == 290)
.Sum(a => a.Balance);

Like this:
myBalanceSum = account.Where(x => x.name == 'stocks' && x.userid == 290 ).Sum(x => x.Balance);

Related

Get Values from single column based on condition

I have query and I can display values based on condition in SQL. But how can write C# LINQ query is my question.
SELECT Value
FROM db.table
WHERE xxId = 1 AND YYid = 2 AND IsActive = '1' AND IsDeleted = '0'
Result
NNNN
MMMM
TTTT
VVVV
LLLL
I need same query in LINQ C#
var results = db.table
.Select(a => a.xxid == xxid && a.yyid == id &&
a.IsActive && !a.IsDeleted).value;
var results = db.table
.Where(a => a.xxid == xxid && a.yyid == id && a.IsActive && !a.IsDeleted)
.Select(a => a.value)
.ToList();

LINQ conditional query where value might be null

I'm trying to write a query to select data from database. I have the following code :
from notes in ctx.Notes
.Where(x => x.UserId== user.UserId
|| x.UserId == user.FamilyId
|| x.UserId == user.CompanyId).DefaultIfEmpty()
The problem with this is that the FamilyId and CompanyId are both nullable types and may not have any value at all which corrupts the whole query. How can I rewrite it so it only looks for FamilyId/CompanyId if they have values?
Create condition query:
var users = ctx.Notes.Where(x => x.UserId == user.UserId);
if (user.FamilyId != null)
{
users = users.Union(ctx.Notes.Where(x => x.UserId == user.FamilyId));
}
if (user.CompanyId != null)
{
users = users.Union(ctx.Notes.Where(x => x.UserId == user.CompanyId ));
}
var result = users.ToArray();
Simple, just add an AND clause to check if it's not null:
from notes in ctx.Notes.Where(x => x.UserId== user.UserId || (user.FamilyId ! =null && x.UserId == user.FamilyId) || (user.CompanyId !=null && x.UserId == user.CompanyId)).DefaultIfEmpty()

VB.NET to C# Linq

I have the following LINQ
Dim z = (From d In db.GPSdevice
Where d.CompanyId = currentuser.CompanyId And d.Type = "Truck" Or d.Type = "Trailer"
Order By d.ListOrder Descending
Group d By d.Driver Into g = Group
Select g.FirstOrDefault())
I try to convert it to c#
var z = db.GPSdevices
.Where(p => p.CompanyId == companyID && p.Type == "Truck" || p.Type == "Trailer")
.OrderByDescending(p => p.ListOrder)
.GroupBy(p => p.Driver)
.Select(g => new { Group = g });
but not sure, how to convert Select g.FirstOrDefault()...
You can use the query syntax in C# too, no need to rewrite using the extension methods directly:
var z = (from d In db.GPSdevice
where (d.CompanyId == currentuser.CompanyId) && (d.Type == "Truck") || (d.Type == "Trailer")
orderby d.ListOrder descending
group d by d.Driver into g = group
select g.FirstOrDefault())
Just call g.FirstOrDefault() in your Select
var z = db.GPSdevices
.Where(p => p.CompanyId == companyID && p.Type == "Truck" || p.Type == "Trailer")
.OrderByDescending(p => p.ListOrder)
.GroupBy(p => p.Driver)
.Select(g => g.FirstOrDefault());

How to Select new model list after GroupBy mothod in Linq?

I want select grouped rows to a new model list.this is my code:
List<Model_Bulk> q = (from a in db.Advertises
join c in db.Companies on a.AdvertiseCompanyID equals c.CompanyID
where a.AdvertiseActive == true
&& a.AdvertiseExpireDate.HasValue
&& a.AdvertiseExpireDate.Value > DateTime.Now
&& (a.AdvertiseObjectType == 1
|| a.AdvertiseObjectType == 2)
select c)
.GroupBy(a => a.CompanyID).Select(a => new Model_Bulk
{
CompanyEmail = a.CompanyContactInfo.Email,
CompanyID = a.CompanyID,
CompanyName = a.CompanyName,
Mobile = a.CompanyContactInfo.Cell,
UserEmail = a.User1.Email,
categories = a.ComapnyCategories
}).ToList();
After group by, i can not use Select and naturally this syntax error raised:
System.Linq.IGrouping' does not contain a definition for 'CompanyContactInfo' and no extension method 'CompanyContactInfo' accepting a first argument of type
System.Linq.IGrouping' could be found (are you missing a using directive or an assembly reference?)
If i try with SelectMany() method.but the result will repeated and groupby method not work properly:
List<Model_Bulk> q = (from a in db.Advertises
join c in db.Companies on a.AdvertiseCompanyID equals c.CompanyID
where a.AdvertiseActive == true
&& a.AdvertiseExpireDate.HasValue
&& a.AdvertiseExpireDate.Value > DateTime.Now
&& (a.AdvertiseObjectType == 1
|| a.AdvertiseObjectType == 2)
select c)
.GroupBy(a => a.CompanyID).SelectMany(a => a).Select(a => new Model_Bulk
{
CompanyEmail = a.CompanyContactInfo.Email,
CompanyID = a.CompanyID,
CompanyName = a.CompanyName,
Mobile = a.CompanyContactInfo.Cell,
UserEmail = a.User1.Email,
categories = a.ComapnyCategories
}).ToList();
Instead of .SelectMany(a => a) you can use .Select(g => g.First()).That will give you the first item of each group.
(from a in db.Advertises
join c in db.Companies on a.AdvertiseCompanyID equals c.CompanyID
where a.AdvertiseActive == true && a.AdvertiseExpireDate.HasValue && a.AdvertiseExpireDate.Value > DateTime.Now && (a.AdvertiseObjectType == 1 || a.AdvertiseObjectType == 2)
select c)
.GroupBy(a => a.CompanyID)
.Select(g => g.First())
.Select(a => new Model_Bulk
{
CompanyEmail = a.CompanyContactInfo.Email,
CompanyID = a.CompanyID,
CompanyName = a.CompanyName,
Mobile = a.CompanyContactInfo.Cell,
UserEmail = a.User1.Email,
categories = a.ComapnyCategories
}).ToList();
Note that this might not be supported, if that is the case add an AsEnumerable call before .Select(g => g.First())
You should understand that after you do GroupBy() in your LinQ expresstion you work with a group so in your example it will be good to write like this:
List<Model_Bulk> q =
(from a in db.Advertises join c in db.Companies on a.AdvertiseCompanyID equals c.CompanyID
where a.AdvertiseActive == true
&& a.AdvertiseExpireDate.HasValue
&& a.AdvertiseExpireDate.Value > DateTime.Now
&& (a.AdvertiseObjectType == 1 || a.AdvertiseObjectType == 2)
select c)
.GroupBy(a => a.CompanyID)
.Select(a => new Model_Bulk
{
CompanyEmail = a.First().CompanyContactInfo.Email,
CompanyID = a.Key, //Note this line, it's can be happened becouse of GroupBy()
CompanyName = a.First().CompanyName,
Mobile = a.First().CompanyContactInfo.Cell,
UserEmail = a.First().User1.Email,
categories = a.First().ComapnyCategories
}).ToList();
Instead you could try something like this, instead of mixing query expressions and methods... (using FirstOrDefault() in the where / select as necessary)
(from a in db.Advertises
join c in db.Companies on a.AdvertiseCompanyID equals c.CompanyID
group a by new { a.CompanyId } into resultsSet
where resultsSet.AdvertiseActive == true && resultsSet.AdvertiseExpireDate.HasValue && resultsSet.AdvertiseExpireDate.Value > DateTime.Now && (resultsSet.AdvertiseObjectType == 1 || resultsSet.AdvertiseObjectType == 2)
select new Model_Bulk
{
CompanyEmail = resultsSet.CompanyContactInfo.Email,
CompanyID = resultsSet.CompanyID,
CompanyName = resultsSet.CompanyName,
Mobile = resultsSet.CompanyContactInfo.Cell,
UserEmail = resultsSet.User1.Email,
categories = resultsSet.ComapnyCategories
}).ToList();

Only parameterless constructors and initializers are supported in LINQ to Entities

While trying a sem-complex query to display some ListView content on the page I got stuck on the famous "Only parameterless contstructor and initializers are supported in LINQ to Entities" error.
Here is the code I used ... I can't find a place where I initialized something inside the query with parameters ....
protected void ArtistsList()
{
Guid cat1 = new Guid("916ec8ae-8336-43b1-87c0-8536b2676560");
Guid cat2 = new Guid("92f2a07f-0570-4521-870a-bf898d1e92d6");
var memberOrders = (from o in DataContext.OrderSet
where o.Status == 1 || o.Status == 0
select o.ID);
var memberOrderDetails = (from o in DataContext.OrderDetailSet
where memberOrders.Any(f => f == o.Order.ID)
select o.Product.ID );
var inventoryItems = (from i in DataContext.InventoryItemSet
select i.Inventory.Product.ID);
var products = (from p in DataContext.ProductSet
join m in DataContext.ContactSet on p.ManufacturerID equals m.ID
where p.Active == true
&& p.ShowOnWebSite == true
&& p.Category.ID != cat1
&& p.Category.ID != cat2
&& p.AvailableDate <= DateTime.Today
&& (p.DiscontinuationDate == null || p.DiscontinuationDate >= DateTime.Today)
&& memberOrderDetails.Any(f => f != p.ID)
&& inventoryItems.Any(f => f == p.ID)
select new { ContactID = m.ID, ContactName = m.Name });
artistsRepeater.DataSource = products;
artistsRepeater.DataBind();
Response.Write("PRODUCT COUNT: " + products.Count());
}
The error itself pops on the line artistsRepeater.DataSource = products;
I tried to comment the lines && memberOrderDetails.Any(f => f != p.ID) and && inventoryItems.Any(f => f == p.ID) , still doesn't change anything
Any hints ?
[edit]
With LINQpad, it works with the join but with it is bugging on the commented line
(from p in Products
join m in Members on p.ManufacturerID.Value equals m.ID
where p.Active == true
&& p.ShowOnWebSite == true
&& p.AvailableDate <= DateTime.Today
&& (p.DiscontinuationDate == null || p.DiscontinuationDate >= DateTime.Today)
//&& (from od in MemberOrderDetails where (from mo in MemberOrders where mo.Status == 1 || mo.Status == 0 select mo.ID).Any(f => f == od.ID) select od.Product.ID)
&& (from inv in InventoryItems select inv.Inventory.ProductID).Any(i => i.Value == p.ID)
select m).Distinct()
[edit-2]
It seems that this query in LINQpad is ok :
(from p in Products
join m in Members on p.ManufacturerID.Value equals m.ID
where p.Active == true
&& p.ShowOnWebSite == true
&& p.AvailableDate <= DateTime.Today
&& (p.DiscontinuationDate == null || p.DiscontinuationDate >= DateTime.Today)
&& !(from od in MemberOrderDetails where (from mo in MemberOrders where mo.Status == 1 || mo.Status == 0 select mo).Any(f => f.ID == od.ID) select od.Product.ID).Any(i => i == p.ID)
&& (from inv in InventoryItems select inv.Inventory.ProductID).Any(i => i.Value == p.ID)
select m)
OK, this is subtle, but what if you change your LINQPad query from:
(from p in Products
join m in Members
on p.ManufacturerID.Value equals m.ID
where p.Active == true
&& p.ShowOnWebSite == true
&& p.AvailableDate <= DateTime.Today
&& (p.DiscontinuationDate == null || p.DiscontinuationDate >= DateTime.Today)
&& (from od in MemberOrderDetails
where (from mo in MemberOrders
where mo.Status == 1 || mo.Status == 0
select mo.ID).Any(f => f == od.ID)
select od.Product.ID)
&& (from inv in InventoryItems
select inv.Inventory.ProductID).Any(i => i.Value == p.ID)
...to:
(from p in Products
join m in Members
on p.ManufacturerID.Value equals m.ID
where p.Active == true
&& p.ShowOnWebSite == true
&& p.AvailableDate <= DateTime.Today
&& (p.DiscontinuationDate == null || p.DiscontinuationDate >= DateTime.Today)
&& (from od in MemberOrderDetails
where (from mo in MemberOrders
where mo.Status == 1 || mo.Status == 0
select mo).Any(f => f.ID == od.ID) // NOTE!
select od.Product.ID)
&& (from inv in InventoryItems
select inv.Inventory.ProductID).Any(i => i.Value == p.ID)
Why? I think type inference might be doing you wrong here. I've seen a similar thing with DateTimes.
The most likely culprit is:
select new { ContactID = m.ID, ContactName = m.Name }
This is because anonymous types do not have parameterless constructors. What's odd about that is that anonymous types are de riguer in LINQ to Entities. I just don't see any other line that could be offending.
First try removing that line and see if the error goes away. At least we'll know if it's that line or not. Then we can focus on figuring out why.
Edit: What are the types of OrderSet.ID, Product.ID and Order.ID and ContactSet.ID? Are any of them Guid and implicitly the Guid constructor is being called?
Convert to a list first, then call your select statement:
var res = abc.getEmployess().toList().select(x => new keyvaluepair<int, string>(x.EmpID, x.EmpName.tostring)).tolist();

Categories

Resources