I have this error can't implicitly convert Enumerable row collection <short> to short in this line of code:
Month = (from item in query select (short)item.Month);
I want to know why and why I can't find distinct() or count method in query variable.
here is my method:
public bool IsEnableAccPosting(
string CompanyCode, DateTime FromDate, DateTime ToDate, out short Month)
{
try
{
o_dmDebitAccounts = new dmDebitAccounts(sysInfo);
bool IsEnable = false;
DataTable dt = o_dmDebitAccounts.GetDebitInterestAccPeriods(CompanyCode);
var query = from data in dt.AsEnumerable()
where data.Field<DateTime>("StartDate") == FromDate &&
data.Field<DateTime>("EndDate") == ToDate
select new
{
Month = Convert.ToInt16(data.Field<short>("Month")),
Year = Convert.ToInt16(data.Field<short>("Year"))
};
Month = (from item in query select (short)item.Month); //heres the error
The field is already typed as an Int16 in the linq query that is performing the operation. You dont need to cast it.
try the following code taken from here
if (query.Any())
{
var result = query.First();
// Console.WriteLine("Results: {0}", result.Month);
Month = result.Month;
}
Related
I am trying to query a comma delimited string using PredicateBuilder. My data set has DAYS in TR format which means Tuesday and Thursday, but my parameter query string will be passed in this way: Day=T,R. My query does not return any data right now so I guess have to use like '%' to get data. Can anyone tell me where the problem is in my linq query below:
public List<myTable> Get(string filter1 = null, string Day = null)
{
if (string.IsNullOrWhiteSpace(filter1) && string.IsNullOrWhiteSpace(Day) )
return new List<myTable>();
IQueryable<myTable> qry = db.myTable.AsQueryable();
var searchPredicate = PredicateBuilder.True<myTable>();
if (filter1 !=null){
searchPredicate = searchPredicate.And(a => a.Column1.Contains(filter1)
}
if (Day != null)
{
//split day string
string[] items = Day.Split(',');
foreach (var item in items)
{
searchPredicate = searchPredicate.And(a => items.Contains("%" + a.DAYS + "%"));
}
}
return qry.where(searchPredicate).ToList();
}
Or, how to create a where Predicate like this: where column1='filter' and (DAYS like 'T%' or DAYS like 'M%') ? Thanks.
I have a linq query which joins a couple of tables and returns the value into an object. The query was working fine, till i added a where clause to in. Aftre the where clause, my query returns null.
Here's the code:
List<Int32> resourceSupervisorIdList = new List<Int32>();
resourceSupervisorIdList.Add(searchCriteriaTimesheet.ResourceId);
foreach (resource res in allSubordinateResources)
{
if (!resourceSupervisorIdList.Contains(res.id_resource))
resourceSupervisorIdList.Add(res.id_resource);
}
using (tapEntities te = new tapEntities())
{
var timesheetAll = (from tsh in te.timesheet_header
join rs in te.resources on tsh.id_resource equals rs.id_resource
join tsd in te.timesheet_detail on tsh.id_timesheet equals tsd.id_timesheet
where (resourceSupervisorIdList.Contains(rs.id_resource_supervisor))
select new TimesheetHeaderDetailsItem()
{
OrganizationId = rs.id_organization,
ProjectId = tsd.id_project,
StartDate = tsh.dte_period_start,
EndDate = tsh.dte_period_end,
ApprovedDate = tsh.dte_approved,
RejectedDate = tsh.dte_rejected,
SubmittedDate = tsh.dte_submitted,
});
if (timesheetAll == null || timesheetAll.Count() == 0)
{
return result;
}
}
Now, after adding the where clause, the code runs into the if condition. There are matching records in the table, but still i'm not able to get any records.
rs.id_resource_supervisor
is of type int in the mysql db.
I have created a DataTable. I have populated the rows of the DataTable after some operations.
I am very new to Linq I want to Get the Top "N" Records from the DataTable implementing also some paging.
Let dataTable is the DataTable having some data.
I am need something like this
var Query = from d in dataTable
Order by columnName
skip( some records pageSize * pageNumber)
Select top N from dataTable
The column Name, Page size ,pageNumber and the N will passed as arguments
Try this:
var query = dataTable.AsEnumerable()
.OrderBy(c => c.columnName)
.Select(r => new {...})
.Skip(10)
.Take(5)
Try this,
int numberOfObjectsPerPage = 20;
var queryResultPage = dataTable.OrderBy(c => c.columnName).Select(r => r).Skip(numberOfObjectsPerPage * pageNumber).Take(numberOfObjectsPerPage);
Try this
var Query = dataTable.Select(o=>o).OrderBy(o=>o.columnName).Skip(pageSize * pageNumber).Take(N);
EDIT
For pass column name you should to add this code
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
And then you could call it in this way
var values = dataTable.OrderByField("columnName");
I have a array of string say:
String[] Fields=new String[]{RowField,RowField1}
In which I can use the below query to get the values by specifying the values is query i.e RowField and RowField1:
var Result = (
from x in _dataTable.AsEnumerable()
select new
{
Name = x.Field<object>(RowField),
Name1 = x.Field<object>(RowField1)
})
.Distinct();
But if suppose I have many values in the Array like:
String[] Fields= new String[]
{
RowField,
RowField1,
RowField2,
.......
RowField1000
};
How can I use the query here without specifying each of the rowfield in the query?
How can i iterate through the array items inside the LINQ?
According to some suggestions in LINQ query and Array of string I am trying to get the result using the code below.
var result = (from row in _dataTable.AsEnumerable()
let projection = from fieldName in fields
select new {Name = fieldName, Value = row[fieldName]}
select projection.ToDictionary(p=>p.Name,p=>p.Value))
.Distinct();
But the problem is it does not return the distinct values.Any ideas?
Start with distinct DataRows by using this overload of Distinct():
_dataTable.AsEnumerable().Distinct(new DataRowEqualityComparer())
Where DataRowEqualityComparer is:
public class DataRowEqualityComparer : IEqualityComparer<DataRow>
{
public bool Equals(DataRow x, DataRow y)
{
return x.ItemArray.SequenceEqual(y.ItemArray);
}
public int GetHashCode(DataRow obj)
{
return string.Join("", obj.ItemArray).GetHashCode();
}
}
I want to search records which two column combination equals to the parameter, why it does not work?
public RDCheck SearchByUserPlusId(string uid)
{
RDCheckDataContext dc = new RDCheckDataContext(_connString);
var query = (from r in dc.RDChecks
where (r.login + r.id).Equals(uid)
select r).FirstOrDefault();
return query;
}
for example, one record in table is
id:4/login:test
So I pass parameter uid=test4 but it returns null, why?
Use ToString() before the concatenation
public RDCheck SearchByUserPlusId(string uid)
{
RDCheckDataContext dc = new RDCheckDataContext(_connString);
var query = (from r in dc.RDChecks
where (r.login.ToString() + r.id.ToString()).Equals(uid)
select r).FirstOrDefault();
return query;
}