hi guys i am stuck converting below sql to LINQ query.
all i want is to have maximum number from list of (FA-00001 ,FA-00059)
SELECT MAX(CAST(SUBSTRING(ReferenceId, PATINDEX('%-%', ReferenceId) + 1, LEN(ReferenceId) - PATINDEX('%-%', ReferenceId)) AS int)) AS MaxReferenceId FROM [ClientRC].[dbo].[EHO_Action]
is this possible to convert to LINQ? thanks
An alternative approach using anonymous projection:
var y = (from record in
(from record in db.ClientRC
select new
{
Group = "x",
ReferenceNumber = Convert.ToInt32(record.ReferenceId.Split('-')[1])
})
group record by new { record.Group } into g
select new
{
MaxReferenceId = g.Max(p => p.ReferenceNumber)
});
http://msdn.microsoft.com/en-us/library/bb386972.aspx
var myvar = (from v in db.object where v!=null select v.id).Max();
MSDN has lots of examples for stuff like this.
Or, you can execute queries directly against a datacontext if you're using entity framework. Just make sure if you're doing anything with parameters you're parameterizing the query and not taking user input directly into it.
http://msdn.microsoft.com/en-us/library/ee358769.aspx
Try this..
var list = DBContext.EHO_Action
.Where(x => x.YourListColumn != null)
.Select(x => x.YourListColumn).ToList(); // Take the list (FA-00001 ,FA-00059) from db to a list
var maxNo = list.Max(x => Convert.ToInt32(x.Split('-')[1]));
Please change the context and column names according to your Linq context.
If you want to use sql you can do it this way..
var list = DBContext.ExecuteQuery<string>("select yourreqrdcolumn from [ClientRC].[dbo].[EHO_Action]");
Related
I need to get the count of IN / in / In from SoccerStatus regardless if the records are saved in upper case, lower case or a combination of both ie IN or in or In from SQLite database in Xamarin Forms. How can I achieve that ?
var count_in = (from x in conn.Table<SoccerAvailability>().Where(x => x.SoccerStatus == IN) select x).Count();
Use string.Equals and tell it to ignore case...
var count_in = (from x in conn.Table<SoccerAvailability>().Where(x => string.Equals(x.SoccerStatus, "IN", StringComparison.OrdinalIgnoreCase)) select x).Count();
EDIT: Per your comment I see that the Linq provider you're using doesn't support string.Equals. You can try the following which should be more portable but possibly a bit slower...
var count_in = (from x in conn.Table<SoccerAvailability>().Where(x => x.SoccerStatus.ToUpper() == "IN") select x).Count();
I am doing some queries for Data Visualization and rely on GroupBy, Avg, Sum, and similar functions to get a good dataset from the DB.
I would like to use something similar to GroupBy with ServiceStack OrmLite. On the ShippersExample page I see the following query. Is there an easier or better way to do this?
For example, I have a 'location' column and would like to find the top 5 locations of an entry, and list these locations with the amount of times it occurs. I only have 1 table, so no need for joins.
var rows = db.SqlList<ShipperTypeCount>(
"SELECT {0}, COUNT(*) AS Total
FROM Shippers
GROUP BY {0}
ORDER BY Total".Fmt("ShipperTypeId".SqlColumn()));
You can also use a SqlExpression, e.g:
var rows = db.SqlList<ShipperTypeCount>(
db.From<Shipper>()
.GroupBy(x => x.ShipperTypeId)
.OrderBy("Total")
.Select(x => new { x.ShipperTypeId, Total = Sql.As(Sql.Count("*"), "Total") }));
Alternatively instead of using a concrete POCO you can use a generic dictionary to populate a dictionary of ShipperTypeId => Total, e.g:
var q = db.From<Shipper>()
.GroupBy(x => x.ShipperTypeId)
.OrderBy("2")
.Select(x => new { x.ShipperTypeId, Total = Sql.Count("*") });
var results = db.Dictionary<int, int>(q);
I have the list of ProjectId like 14,15,18 and i want to search those items from my datatable using linq.
now i have created the query like
IEnumerable<DataRow> drProjList = from a in dtProj.AsEnumerable()
where a.Field<int>("ProjectId")
.ToString()
.Contains(projFilter)
select a;
but i am not getting the 0 elements.
can any body suggest me any other way like IN operator in linq.
thanks in advance
EDIT
projFilter is the pure string which have the 14,15,18,... project ids.
String's "contains" isn't really an option here. You should convert projFilter into a proper list of integers first.
var projFilter2 = new HashSet<int>(projFilter.Split(',').Select(i => int.Parse(i)));
and only then check if it contains the desired number.
IEnumerable<DataRow> drProjList =
from a in dtProj.AsEnumerable()
where projFilter2.Contains(a.Field<int>("ProjectId"))
select a;
I don't know much about the AsEnumerable(), but I would have done it the other way round, something like this:
List<int> intProjFilter = new List<int>();
foreach(string filter in projFilter.Split(','))
intProjFilter.Add(int.Parse(filter));
from a in dtProj
where projFilter.Contains(a.ProjectID)
select a;
Let me know if this helps
You need to parse the project filter into collection of integers first.
var projectIds = projFilter.Split(',').Select(x => Convert.ToInt32(x)).ToList();
var drProjList =
from a in dtProj.AsEnumerable()
where projectIds.Contains(a.ProjectId)
select a;
Maybe something like this:
IEnumerable<DataRow> drProjList =
(
from a in dtProj.AsEnumerable()
where projFilter.Contains(a.Field<int>("ProjectId").ToString())
select a;
)
Or you can simply do this as well:
IEnumerable<DataRow> drProjList=dtProj.AsEnumerable()
.Where(a=>projFilter
.Contains(a.Field<int>("ProjectId")
.ToString()));
I don't know c# well so i am trying to give answer in vb.net hope that will help you.
Dim dtProj As DataTable
dtProj = FillProjectList()
Dim projIdFilter() As Integer = {14, 15, 16}
Dim drRow = From p In dtProj.AsEnumerable _
Where projIdFilter.Contains(p.Field(Of Integer)("ProjectId")) _
Select p
Thank you...
I have a label to show BookName. I get it from table which name tblBooks. I don't know how to show Book Name into the label.
var query = from b in dc.tblBooks.Where(b=>b.BookID == 'B01') select b;
Can you help me know.
Your query as written will return a collection of books—IQueryable<Book>. If you're sure there will only be one result in this query, you can call SingleOrDefault, which will execute the query immediately and give you the actual book.
var Book = dc.tblBooks.Where(b => b.BookID == 'B01').SingleOrDefault();
if (Book != null)
myLabel.Text = Book.BookName;
Or you can simply say:
var Book = dc.tblBooks.SingleOrDefault(b => b.BookID == 'B01');
Which does the same thing.
If you're 110% sure there will always be a result, and you don't want to check for null, then you can use Single, which will do the same thing, except throw an exception if no results are found, where SingleOrDefault simple returns null.
var Book = dc.tblBooks.Single(b=>b.BookID == 'B01');
myLabel.Text = Book.BookName;
Try:
label.Text = query.FirstOrDefault().BookName;
This feels like a completely basic question, but, for the life of me, I can't seem to work out an elegant solution.
Basically, I am doing a LINQ query creating a new object from the query. In the new object, I want to generate a auto-incremented number to allow me to keep a selection order for later use (named Iter in my example).
Here is my current solution that does what I need:
Dim query2 = From x As DictionaryEntry In MasterCalendarInstance _
Order By x.Key _
Select New With {.CalendarId = x.Key, .Iter = 0}
For i = 0 To query2.Count - 1
query2(i).Iter = i
Next
Is there a way to do this within the context of the LINQ query (so that I don't have to loop the collection after the query)?
Pardon me for doing this in C# not sure exactly the syntax in VB.NET:
MasterCalendarInstance
.OrderBy(x => x.Key)
.Select((x, ixc) => new { CalendarId = x.Key, Iter = ixc });
I don't know if this is possible in VB, but in C# one uses a closure:
int count = 0
var res = from x in MasterCalendarInstance
order by x.Key
select new {
CalendarId = x.Key,
Iter = count++
};
The above solutions could be summed up in VB.NET like this :
MasterCalendarInstance _
.OrderBy(Function (x) x.Key) _
.Select(Function (x, ixc) New With { .CalendarId = x.Key,
.Iter = ixc })
I ran into this post while trying to solve a similar problem with a List(of String).
I'm posting my workaround in hopes that it may be adopted to resolve your issue, but more for anyone else who runs into this issue with a List(Of T).
Dim list As New List(Of String)
list.Add("Test1")
list.Add("Test2")
list.Add("Test3")
Dim var = list.Select(Function(s) New With {.Name = s, .RecordID = list.IndexOf(s)})
Hope this helps!