My Datatable is in following format.
I want to get the Netfare Where Sector is 1 and then similarly I want to get Netfare Where Sector is 2.
Thanks
You can use the DataTable.Select method to filter the result.
var sector1Results = dt.Select("Sector = 1");
var sector2Results = dt.Select("Sector = 2");
You can also use DataTable.AsEnumerable method to achieve the same
var result1 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).Select(x => x.Field<int>("Sector1"));
var result2 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 2).Select(x => x.Field<int>("Sector2"));
To select the DataRow collection, You can use this
List<DataRow> collection1 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).ToList();
List<DataRow> collection2 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).ToList();
You can also merge those condition in single statement (if you want)
List<DataRow> collection = new DataTable().AsEnumerable().Where(x => x.Field<int>("Sector") == 1 || x.Field<int>("Sector") == 2).ToList();
Related
I'm trying to convert this SQL Query into Core EF:
SELECT w.IdShippingBatch, w.BookingNumber, COUNT(c.IdShippingOrder) AS ShippingOrders, w.CreatedOn, w.ModifiedOn
FROM dbo.Shipping`enter code here`Batch AS w LEFT OUTER JOIN
dbo.ShippingOrders AS c ON w.IdShippingBatch = c.IdShippingBatch
WHERE (w.IdCompany = 2) AND (w.IdDealer = 1)
GROUP BY w.IdShippingBatch, w.BookingNumber, w.CreatedOn, w.ModifiedOn
I have tried multiple solutions, including several here. My latest attempt looks like:
var data = (from w in _context.ShippingBatch
join c in _context.ShippingOrders on w.IdShippingBatch equals c.IdShippingBatch into t1
where w.IdCompany == idCompany && w.IdDealer == idDealer
from t2 in t1.DefaultIfEmpty()
group t2 by new { w.IdShippingBatch, w.BookingNumber, w.CreatedOn, w.ModifiedOn } into t3
select new ShippingBatchDTO
{
IdShippingBatch = t3.Key.IdShippingBatch,
BookingNumber = t3.Key.BookingNumber,
ShippingOrders = t3.Count(),
CreatedOn = t3.Key.CreatedOn,
ModifiedOn = t3.Key.ModifiedOn
});
I have also tried adding t3.count(m => m.something != null), but that throws an error.
One major point of EF is to map the relationship between entities so that you can leverage LINQ and let EF compose an SQL query rather than trying to replace SQL with LINQ-QL.
If your ShippingBatch is mapped with a collection of ShippingOrders...
var batches = _context.ShippingBatch
.Where(x => x.IdCompany == idCompany && x.IdDealer == idDealer)
.Select(x => new ShippingBatchDTO
{
IdShippingBatch = x.IdShippingBatch,
BookingNumber = x.BookingNumber,
ShippingOrders = x.ShippingOrders.Count(),
CreatedOn = x.CreatedOn,
ModifiedOn = x.ModifiedOn
}).ToList();
If your ShippingBatch does not have a collection of ShippingOrders, but your ShippingOrder reference an optional ShippingBatch.
var batches = _context.ShippingOrder
.Where(x => x.ShippingBatch != null
&& x.ShippingBatch.IdCompany == idCompany
&& x.ShippingBatch.IdDealer == idDealer)
.GroupBy(x => x.ShippingBatch)
.Select(x => new ShippingBatchDTO
{
IdShippingBatch = x.Key.IdShippingBatch,
BookingNumber = x.Key.BookingNumber,
ShippingOrders = x.Count(),
CreatedOn = x.Key.CreatedOn,
ModifiedOn = x.Key.ModifiedOn
}).ToList();
That should hopefully get you moving in the right direction. If not, expand your question to include details of what you are seeing, and what you expect to see along with definitions for the applicable entities.
I am trying to write this piece of code that will search the database table and I am trying to search multiple columns. What I have below appears to be the equivalent to WHERE column = "this" AND column2 = "this", what I am trying to do is this WHERE column = "this" OR column2 = "this" How would I accomplish this?
query = query.Where(p => (p.ChckNumber.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.BankAccount.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.Description.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.CheckAmount.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.ClearedDate.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.SentDate.ToString()).Contains(globalSearch.ToString()));
You should be able to do this in-line using the OR operator:
query = query.Where(p =>
p.ChckNumber.ToString().Contains(globalSearch.ToString()) ||
p.BankAccount.ToString().Contains(globalSearch.ToString()) ||
p.Description.ToString().Contains(globalSearch.ToString()) ||
p.CheckAmount.ToString().Contains(globalSearch.ToString()) ||
p.ClearedDate.ToString().Contains(globalSearch.ToString()) ||
p.SentDate.ToString().Contains(globalSearch.ToString())
);
I have the below query that gets Name and TotalPoints as follows:
var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData(Convert.ToInt32(this.ShopInstanceID), 10000, false)
.Where(row => row.RecievedPoints != "n/a")
.GroupBy(row => new { row.Name })
.Select(g => new
{
TotalPoints = g.Sum(x => Convert.ToDouble(x.RecievedPoints) * (x.Weightage.ToString() == "0.00" ? 1 : Convert.ToDouble(x.Weightage))),
Name = g.Key.Name
})
select data).ToList();
I will have data like below:
TotalPoints Name
5 A
10 B
5 C
15 D
5 E
If we observe the above list 5 is most common. I have to fetch that value from "gradeData".
How can I get that?
var mostCommon = gradeData.GroupBy(x => x.TotalPoints)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.First();
The query below gives you the most common point along with all of its associated names:
var result = gradeData.GroupBy(x => x.TotalPoints)
.OrderByDescending(x => x.Count())
.Select(g => new
{
TotalPoints = g.Key,
Names = g.Select(x => x.Name).ToList()
})
.First();
I've seen dozens of posts similar to this, but I just can't get it to work.
Using asp.net MVC framework, I have a table named Contributions that contains a "ContributionDate" column and an "Amount" column. I'm loading the dates and amounts to display in a chart:
var results = db.Contributions.Where(c => c.Amount > 0);
ArrayList xValue = new ArrayList();
ArrayList yValue = new ArrayList();
results.ToList().ForEach(c => xValue.Add(c.ContributionDate));
results.ToList().ForEach(c => yValue.Add(c.Amount));
The above works. Now I'd liked to sum (i.e., total) the Amounts for each year. I've seen examples that are similar to the following, but I'm clearly clueless (in this example, the compiler doesn't like the "c.ContributionDate" in the new{} statement):
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate )
.Select(c => new {Amount = c.Sum(b => b.Amount), Date=c.ContributionDate});
Thanks for your help!
When you perform a GroupBy, the key by which you're grouping elements is represented by the Key property.
Try this:
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate )
.Select(c => new { Amount = c.Sum(b => b.Amount), Date = c.Key });
But this will group items by the entire ContributionDate value, not just by the year. To do that, you'd have to do something like this:
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate.Year)
.Select(c => new
{
Amount = c.Sum(b => b.Amount),
Date = new DateTime(c.Key, 1, 1)
});
But since this appears to be Entity Framework, you probably need to use the CreateDateTime function:
using System.Data.Entity;
...
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate.Year)
.Select(c => new
{
Amount = c.Sum(b => b.Amount),
Date = EntityFunctions.CreateDateTime(c.Key, 1, 1, 0, 0, 0)
});
I want to build dynamic Linq. Following is my code which works fine for one date. But user can select many dates from calendar. And I need to make Linq for all those selected dates.
saleDate = calendarSales.SelectedDate;
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => (Convert.ToDateTime(sale.DATE_TIME).Day == saleDate.Day &&
Convert.ToDateTime(sale.DATE_TIME).Month == saleDate.Month &&
Convert.ToDateTime(sale.DATE_TIME).Year == saleDate.Year)
).ToList();
How to update this query?
You have to build the predicate for your where clause dynamically.
Take a look at the predicatebuilder.
EDIT
Of cause PredicateBuilder supports AND and OR operators.
When using OR you have to start with the initial value of False:
// building the predicate
var pred = PredicateBuilder.False<SaleDetails>();
foreach (var date in MyDateList)
{
pred = pred.Or(sale => sale.DATE_TIME.Date == saleDate.Date);
}
// finally get the data and filter it by our dynamic predicate
List<SaleDetails> saleDetails = GetSaleDetails().Where(pred).ToList();
I'm not sure you need dynamic LINQ here. You should be able to check Where the sale matches Any of the selected dates, like so:
var saleDates = GetSelectedDate();
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date =>
(Convert.ToDateTime(sale.DATE_TIME).Day == date.Day &&
Convert.ToDateTime(sale.DATE_TIME).Month == date.Month &&
Convert.ToDateTime(sale.DATE_TIME).Year == date.Year)
)).ToList();
or checking on the Date property:
var saleDates = GetSelectedDate();
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date =>
Convert.ToDateTime(sale.DATE_TIME).Date == date.Date)).ToList();