How to convert following code to method operator:
var myOrders = from c in customers
where c.Field<string>("Region") == "WA"
from o in orders
where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
&& (DateTime)o["OrderDate"] >= cutoffDate
select new {
CustomerID = c.Field<string>("CustomerID"),
OrderID = o.Field<int>("OrderID")
};
---------or----------
var myOrders = from c in customers
where c.Region == "WA"
from o in orders
where c.CustomerID == o.CustomerID
&& o.OrderDate >= cutoffDate
select new {
CustomerID = c.CustomerID,
OrderID = o.OrderID
};
same code in object form
I'd actually rewrite this as a join - probably via intermediate variables:
var washingtonCustomers = customers.Where(c => c.Field<string>("Region") == "WA");
var recentOrders = orders.Where(o => (DateTime)o["OrderDate"] >= cutoffDate);
var query = washingtonCustomers.Join(recentOrders,
c => c.Field<string>("CustomerID"),
o => o.Field<string>("CustomerID"),
(c, o) => new {
CustomerID = c.Field<string>("CustomerID"),
OrderID = o.Field<int>("OrderID")
});
You can try with this code - based on IEnumerable<KeyValuePair<string, Int32>
public IEnumerable<KeyValuePair<string, Int32>> YourQuery(DateTime date, string code)
{
var result =
from c in customers
where c.Field<string>("Region") == code
from o in orders
where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
&& (DateTime)o["OrderDate"] >= date
select new
{
CustomerID = c.Field<string>("CustomerID"),
OrderID = o.Field<int>("OrderID")
};
return result;
}
Are you just wanting to use the functional Linq syntax instead of query syntax? That would look like:
var myOrders = customers
.Where(c => c.Region == "WA")
.SelectMany(c =>
orders
.Where(o => (o.CustomerID == c.CustomerID)
&& (o.OrderDate > cutoffDate))
.Select(o => new {
CustomerID = c.CustomerID,
OrderID = o.OrderID
})
);
Related
I want to concat multiple string value into single string with comma separated,i tried using aggregate function but it shows cannot convert string to how to fix this issue,
I tried below code
var res = (from e in WYNKContext.SurgeryAssigned.Where(x => x.CmpID == cmpid && x.IsCancelled == false)
select new
{
ID = e.SAID,
UIN = e.UIN,
SurgeryDate = e.SurgeryDate,
SurgeryID = e.SurgeryID,
Surgery = ((from st in WYNKContext.SurgeryTran.
Where(x => x.SurgeryID == e.SurgeryID)
select new
{
desc = icdmaster
.Where(x => x.ID ==
st.IcdSpecialityCode).Select(x =>
x.SpecialityDescription).FirstOrDefault(),
}).ToList()).Aggregate((a, b) => a.desc + "," + b.desc),
}).ToList();
I want Output like inside surgery property like = string1,string 2 ,etc....
without using aggregate i am getting as count in Surgery Property
var res = (from e in WYNKContext.SurgeryAssigned.Where(x => x.CmpID == cmpid && x.IsCancelled == false)
select new
{
ID = e.SAID,
UIN = e.UIN,
SurgeryDate = e.SurgeryDate,
SurgeryID = e.SurgeryID,
Surgery = (from st in WYNKContext.SurgeryTran.Where(x => x.SurgeryID == e.SurgeryID)
select new
{
icd = icdmaster.Where(x => x.ID == st.IcdSpecialityCode).Select(x => x.SpecialityDescription).FirstOrDefault(),
}).ToList(),
}).ToList();
also tried string join :
Surgery = string.Join(",", (from st in WYNKContext.SurgeryTran.Where(x => x.SurgeryID == e.SurgeryID)
select new
{
icd = icdmaster.Where(x => x.ID == st.IcdSpecialityCode).Select(x => x.SpecialityDescription).FirstOrDefault(),
}).ToList()),
but in output i am getting like this
Surgery ={ icd = CORNEA },{ icd = CATARACT/IOL }
can some one tell what i did wrong in string.join.....
The string class has a static method named Join, which takes in a collection of items and a string to join them with, which should work for you here.
If I'm reading your code correctly, it would look something like this:
Surgery = string.Join(",", WYNKContext.SurgeryTran
.Where(surgTran => surgTran.SurgeryID == e.SurgeryID)
.Select(surgTran => icdmaster
.Where(icd => icd.ID == surgTran.IcdSpecialityCode)
.Select(icd => icd.SpecialityDescription)
.FirstOrDefault())),
I have next table:
MyTable
(
ParentId Integer,
Type Integer,
ProdId String,
Date DateTime,
Status Integer
);
I want to query as next:
var res = from tout in myTable.Where(t1 => t1.Type == 1)
join tin in myTable.Where(t2 => t2.Type != 1)
on tout.ParentId equals tin.ParentId
where tout.ProdId == tin.ProdId && tout.Status > tin.Status
orderby tout.Date
select new MyTableStructure
{
...
};
How to write same as IQueryable using lambda?
Something like this
var query1 = myTable.Where(t1 => t1.Type == 1);
var query2 = myTable.Where(t2 => t2.Type != 1);
var join = query1.Join(query2, x => x.ParentId, y => y.ParentId, (query1, query2) => new { query1 , query2 }).Where(o => o.query1.ProdId == o.qyuery2.prodId).......
your order by next and Something
I have following code snippet in c# which is working fine
foreach (var customer in customers.OrderBy(x => x.CustomerId))
{
if (customer.CustomerId != customerId)
{
winningRate = Helper.Utility.WinningRate(settledCustomers, customer.CustomerId).Status;
numberOfBets = customers.Count(x => x.CustomerId == customer.CustomerId);
numberOfWinnings = customers.Count(x => x.CustomerId == customer.CustomerId && x.Win > 0);
averageBet = Helper.Utility.CustomerAverageBet(settledCustomers, customer.CustomerId);
}
var risky = Helper.Utility.CheckRiskyBet(winningRate, numberOfWinnings, numberOfBets, averageBet, customer.Stake, customer.Win);
customer.Status = risky.Status;
customer.Message = risky.Message;
customerId = customer.CustomerId;
}
return customers;
Now I want to convert above code into LINQ expression and for the same I have written following code which is not giving the same output as
var r = from c in customers
let winningRate1 = Helper.Utility.WinningRate(settledCustomers, c.CustomerId).Status
let numberOfBets1 = customers.Count(x => x.CustomerId == c.CustomerId)
let numberOfWinnings1 = customers.Count(x => x.CustomerId == c.CustomerId && x.Win > 0)
let averageBet1 = Helper.Utility.CustomerAverageBet(settledCustomers, c.CustomerId)
let risky1 = Helper.Utility.CheckRiskyBet(winningRate, numberOfWinnings, numberOfBets, averageBet, c.Stake, c.Win)
where c.CustomerId != customerId
orderby c.CustomerId
select new Customer
{
Status = risky1.Status,
Message = risky1.Message,
CustomerId = c.CustomerId
};
where c.CustomerId != customerId
This clearly is wrong because it reduces the number of times the loop runs.
Many let clauses and control flow in the loop can get ugly when converting to query expressions. A multi-statement lambda often is easier and gets you the same functional code benefits:
customers
.OrderBy(x => x.CustomerId)
.Select(c => {
if (customer.CustomerId != customerId)
{
winningRate = Helper.Utility.WinningRate(settledCustomers, customer.CustomerId).Status;
numberOfBets = customers.Count(x => x.CustomerId == customer.CustomerId);
numberOfWinnings = customers.Count(x => x.CustomerId == customer.CustomerId && x.Win > 0);
averageBet = Helper.Utility.CustomerAverageBet(settledCustomers, customer.CustomerId);
}
var risky = Helper.Utility.CheckRiskyBet(winningRate, numberOfWinnings, numberOfBets, averageBet, customer.Stake, customer.Win);
return new Customer
{
Status = risky.Status,
Message = risky.Message,
CustomerId = c.CustomerId
};
});
This code is just a sketch, it has some issues that you can easily fix. For examples I'm assigning to non-local variables. Your code did not explain what those are so I left them alone.
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();
Hello I have a C# lambda expression looks like it should work to me but its returning nothing.
CategoryItems = (db.Items.Include("Pictures").Join(db.Rentals,
i => i.itemID,
r => r.ItemID,
(i, r) => new { Item = i, Rental = r })
.Where(ir => ir.Item.CategoryID == CategoryID && ir.Rental.RentedBy == 0)
.OrderByDescending(ir => ir.Item.ListDate)
.Select(i => new DisplayItem()
{
AvailableForPurchase = i.Item.AvailableForPurchase,
Description = i.Item.Description == string.Empty ? "No Description" : i.Rental.Title,
PostDate = i.Item.ListDate,
PostedBy = i.Item.User.UserName,
PricePerDay = i.Rental.RentalPrice ?? 0.00m,
ItemID = i.Item.itemID,
PhotoURL = i.Item.Pictures.FirstOrDefault().PictureLink
})).ToPagedList(page, 5);
Any help appreciated
var CategoryItems =
from item in db.Items
join rental in db.Rentals on item.itemID equals rental.ItemID
where item.CategoryID == CategoryID && rental.RentedBy == 0
orderby item.ListDate descending
select new DisplayItem
{
AvailableForPurchase = item.AvailableForPurchase,
...
};