I want to obtain the distinct count of a column in my data table.
I have the following so far
public int DocumentsProcessed()
{
var query = from data in this._data
let docID = data.Field<string>("Document ID")
select new
{
docID
};
var query2 = from d in query
select d.docID.Distinct().Count();
var result = query2;
return result;
}
where this._data is
private IEnumerable<DataRow> _data;
But the result is an IEnumerable. I'm looking for just a single integer as an answer.
EDIT: I tried grouping the data first by Document ID column and then counting the groups, but it gave me the wrong number - for example I have 16 rows where all the Document ID are the same, so the Distinct count should be 1 but I was getting 16.
So in your example for every row you're doing a select distinct. I believe what you want is:
var query = from data in this._data
let docID = data.Field<string>("Document ID")
select new
{
docID
};
var distinctCount = query.Distinct().Count();
I suppose that data is DataTable object so try it in this manner
int count = _data.
.AsEnumerable()
.Select(r => r.Field<string>("Document ID"))
.Distinct()
.Count();
Related
Here is my Service table's columns:
id
serverPlace
count
Here is a SQL query which I need to convert it into Linq:
SELECT Service.id,
Service.serverPlace,
sum(Service.count * 12 + MONTH(getdate())) AS sum
FROM Service
GROUP BY Service.id, Service.serverPlace;
I do not know how to convert and implement sum section with Linq.
It should look like this :
var month = DateTime.Now.Month;
var result = await dbContext.Services.GroupBy(r=> new { r.Id, r.ServerPlace })
.Select(r=> new {
r.Key.Id,
r.Key.ServerPlace,
Sum = r.Sum(q=> q.Count*12 + month)
}).ToArrayAsync();
I am trying to write a linq query for one of my dashboard which retrieves data based on some conditions. I want to display records count based on the different status available in my table.
Following is the SQL query in which I am trying to convert into Linq.
select count(id) cnt, 'Available' label from table where date = sysdate
Above query is returning below result in DB IDE. This is the result I want with linq
cnt label
0 Available
I've tried with following linq query but it is returning 0 count and hence result is not being retrieved.
var data = (from a in context
where a.date = System.DateTime.Now
group a in a.id into g
select new {
cnt = g.Count(),
label = 'Available'
}).ToList();
How do I achieve above mentioned result in linq. Your help will be appreciated.
Thanks
-------------EDIT----------------
Updated LINQ query
var data = (from a in context.TableA
where a.id = uniqueID
group a in a.id into g
select new {
cnt = g.Count(),
label = 'Available'
}).Concat(from a in context.TableB
where a.id = uniqueID
group a in a.id into g
select new {
cnt = g.Count(),
label = 'WIP'
}).ToList();
To count the number of elements matching a predicate in a linq query simply use the where clause:
var results =
from a in context
where a.date.Date == DateTime.Now.Date
&& a.id == someIdHere
select a;
var data = new {
count = results.Count(),
label = "Available"
};
Or, in extension method syntax (which I prefer):
var results = context.Where(a => a.date.Date == DateTime.Now.Date && a.id == someIdHere);
var data = new {
count = results.Count(),
label = "Available"
};
Also be careful when comparing a DateTime object with regards to what results you desire; comparing DateTime.Now to a date will likley return false since it will compare the time code as well, use the DateTime.Date property to obtain only the date from the object for the purposes of comparison.
I want to use Linq to select and group DataTable rows... and I want to order those in a descending manner by the "Max" created date in each group... are there any improvements that could be made to this code, in particular can I make the OrderByDescending part of the Linq, for example using:
orderby {... something here...} descending
--- current code ---
DataTable dt = ReadDataTable();
var rows = (from row in dt.AsEnumerable()
where row.Field<bool>("Active") == true
group row by new
{
CollectionId = row.Field<int>("CollectionId"),
CollectionName = row.Field<string>("CollectionName"),
} into grp
select new
{
CollectionId = grp.Key.CollectionId,
CollectionName = grp.Key.CollectionName,
MaxCreated = grp.Max(r => r.Field<DateTime>("Created"))
}).OrderByDescending(r => r.MaxCreated);
You can use the let clause to hold intermediate results in a complex LINQ query, for use in subsequent sorts and selects. In your case you can use it to store the final result for subsequent sorting.
I.e. you can rewrite your Linq without the OrderByDescending() lambda as follows:
DataTable dt = ReadDataTable();
var rows = from row in dt.AsEnumerable()
where row.Field<bool>("Active")
group row by new
{
CollectionId = row.Field<int>("CollectionId"),
CollectionName = row.Field<string>("CollectionName"),
} into grp
let result = new
{
CollectionId = grp.Key.CollectionId,
CollectionName = grp.Key.CollectionName,
MaxCreated = grp.Max(r => r.Field<DateTime>("Created")),
}
orderby result.MaxCreated descending
select result;
I have a linq query where I am reading all the lines of a CSV the file has extra rows at the end that have no data. I need to filter out those rows so that it only has the rows with data
I am using the following query but it still returns like 8000 rows and there are only 52 with data in them.
var query =
from c in
(from line in File.ReadAllLines(excelFile)
let transactionRecord = line.Split(',')
select new Transaction()
{
TxnId = transactionRecord[12],
})
where c.TxnTax != string.Empty
select c;
Not relaly sure why this is happening? Doe anyone have any ideas?
This will give an IEnumerable containing the lines (string[]) having at least one column with data
IEnumerable<string[]> data =
from line in System.IO.File.ReadAllLines("")
let lineData = line.Split(',')
where lineData.Any(cell => !string.IsNullOrEmpty(cell))
select lineData;
This worked
var query =
from c in
(from line in File.ReadAllLines(excelFile)
let transactionRecord = line.Split(',')
select new Transaction()
{
TxnId = transactionRecord[12],
})
where ((string.IsNullOrEmpty(c.TxnId) == false) && (c.TxnId != "Billing Information|Transaction ID"))
select c;
I am using a linq query to obtain a table of customers with their total money amount for each monetary unit exist in my database(this one is ok.)
when show the result of my query with Microsoft Report Viewer the result is like Table 1 but what i want is Table 2, only the customer name like "A" and a cell with all the monetory unit records > 0.
Is there any way you can suggest?
This is my code which produces Table 1:
var query = from kur in kurToplamlist
join cariBilg in db.TBLP1CARIs
on kur.CariIdGetSet equals cariBilg.ID
select new
{
cariBilg.ID,//customerid
EUROBAKIYE = cariBilg.HESAPADI,
cariBilg.K_FIRMAADI,//other column names
cariBilg.K_YETKILIADI,//other column names
cariBilg.K_FIRMATELEFON,//other column names
cariBilg.K_YETKILITELEFON,//other column names
AUDBAKIYE = cariBilg.B_CEPTELEFON,//other column names
MonetaryUnit = String.Concat(kur.KurToplamMiktarGetSet.ToString(), kur.DovizTuruGetSet.ToString()),//concatenates "100" and "TL/USD etc."
};
What i want is to obtain Table 2 in the image
Thank you in advance.
Table image
var query = from kur in kurToplamlist
where kur.KurToplamMiktarGetSet > 0
join cariBilg in db.TBLP1CARIs
on kur.CariIdGetSet equals cariBilg.ID
select new
{
cariBilg.ID,
EUROBAKIYE = cariBilg.HESAPADI,
cariBilg.K_FIRMAADI,
cariBilg.K_YETKILIADI,
cariBilg.K_FIRMATELEFON,
cariBilg.K_YETKILITELEFON,
AUDBAKIYE = cariBilg.B_CEPTELEFON,
TLBAKIYE = String.Concat(kur.KurToplamMiktarGetSet.ToString(), kur.DovizTuruGetSet.ToString()),
};
var dfg = from qre in query
select qre.TLBAKIYE;
var aq = (from qw in query
select new {
qw.ID,
EUROBAKIYE = qw.EUROBAKIYE,
qw.K_FIRMAADI,
qw.K_YETKILIADI,
qw.K_FIRMATELEFON,
qw.K_YETKILITELEFON,
AUDBAKIYE = qw.AUDBAKIYE,
TLBAKIYE = String.Join(",", (from qre in query
where qre.ID == qw.ID
select qre.TLBAKIYE).Distinct())
}).Distinct();
return aq;
This is my answer.