Selecting different rows in LINQ - c#

I have two functions and a table with 2 rows. I want one function to select the first row and the other function to select the second row. I am a bit lost because I am very new to LINQ.
Here is my current code:
public static bool First() {
using (Entities db = new Entities()) {
DateTime FirstValue = (
from a in db.Table
select a.Timestamp
).Single();
public static bool Second() {
using (Entities db = new Entities()) {
DateTime SecondValue = (
from a in db.Table
select a.Timestamp
).Single();
I working with someone else's code and Im new to LINQ so I'm not sure what Single() does as well. I feel as though I do not need it in my code but I am not sure.

How about:
public static bool First() {
using (Entities db = new Entities()) {
DateTime FirstValue = (
from a in db.Table
select a.Timestamp
).FirstOrDefault();
public static bool Second() {
using (Entities db = new Entities()) {
DateTime SecondValue = (
from a in db.Table
select a.Timestamp
).Skip(1).FirstOrDefault();

#dkackman provided correct answer (use First/FirstOrDefault and Skip methods), but I want to mention that you can avoid mixing query syntax and method syntax, and methods could be simplified to:
public static DateTime First()
{
return GetByIndex(0);
}
public static DateTime Second()
{
return GetByIndex(1);
}
public static DateTime GetByIndex(int index)
{
using (Entities db = new Entities())
return db.Table.Select(a => a.TimeStamp).Skip(index).First();
}

Try like this,
private void First()
{
using (WinEntitie obj = new WinEntitie())
{
var FirstValue = (from a in obj.Employees select a.EmpName).Take(1);
}
}
private void Sec()
{
using (WinEntitie obj = new WinEntitie())
{
var FirstValue = (from a in obj.Employees orderby a.EmpID ascending select a.EmpName ).Skip(1).First();
}
}

Use common method for like this one what ever value you want to skip just pass it to the index. and also use the FirstOrDefault because the corresponding value returns null means it will take care or otherwise getting execption.
public static DateTime GetByIndex(int index)
{
using (Entities db = new Entities()) {
return db.Table.Select(a => a.TimeStamp).Skip(index).FirstOrDefault();
}
return null;
}

I was overwhelmed with LINQ that i should simply use a 'where' statement to locate something in my query...maybe I need a break

Related

Linq Expression Query with In clause [duplicate]

This question already has answers here:
Linq to Entities - SQL "IN" clause
(9 answers)
Closed 8 years ago.
How to make a where in clause similar to one in SQL Server?
I made one by myself but can anyone please improve this?
public List<State> Wherein(string listofcountrycodes)
{
string[] countrycode = null;
countrycode = listofcountrycodes.Split(',');
List<State> statelist = new List<State>();
for (int i = 0; i < countrycode.Length; i++)
{
_states.AddRange(
from states in _objdatasources.StateList()
where states.CountryCode == countrycode[i].ToString()
select new State
{
StateName = states.StateName
});
}
return _states;
}
This expression should do what you want to achieve.
dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))
This will translate to a where in clause in Linq to SQL...
var myInClause = new string[] {"One", "Two", "Three"};
var results = from x in MyTable
where myInClause.Contains(x.SomeColumn)
select x;
// OR
var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));
In the case of your query, you could do something like this...
var results = from states in _objectdatasource.StateList()
where listofcountrycodes.Contains(states.CountryCode)
select new State
{
StateName = states.StateName
};
// OR
var results = _objectdatasource.StateList()
.Where(s => listofcountrycodes.Contains(s.CountryCode))
.Select(s => new State { StateName = s.StateName});
I like it as an extension method:
public static bool In<T>(this T source, params T[] list)
{
return list.Contains(source);
}
Now you call:
var states = _objdatasources.StateList().Where(s => s.In(countrycodes));
You can pass individual values too:
var states = tooManyStates.Where(s => s.In("x", "y", "z"));
Feels more natural and closer to sql.
public List<Requirement> listInquiryLogged()
{
using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
var result = from Q in dt.Requirements
where inq.Contains(Q.ID)
orderby Q.Description
select Q;
return result.ToList<Requirement>();
}
}
The "IN" clause is built into linq via the .Contains() method.
For example, to get all People whose .States's are "NY" or "FL":
using (DataContext dc = new DataContext("connectionstring"))
{
List<string> states = new List<string>(){"NY", "FL"};
List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();
}
from state in _objedatasource.StateList()
where listofcountrycodes.Contains(state.CountryCode)
select state
This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.
Problem:
Let say we have document table. Schema as follows
schema : document(name,version,auther,modifieddate)
composite Keys : name,version
So we need to get latest versions of all documents.
soloution
var result = (from t in Context.document
where ((from tt in Context.document where t.Name == tt.Name
orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
select t).ToList();
public List<State> GetcountryCodeStates(List<string> countryCodes)
{
List<State> states = new List<State>();
states = (from a in _objdatasources.StateList.AsEnumerable()
where countryCodes.Any(c => c.Contains(a.CountryCode))
select a).ToList();
return states;
}

How to pass a list of strings through webapi and get the results without those strings?

My code already gets the table without containing a string. How can I get a list without containing a list of strings? I want to get the result of SELECT * FROM table WHERE column NOT IN ('x' ,'y');
public IEnumerable<keyart1> Get(string keyword)
{
List<keyart1> keylist;
using (dbEntities5 entities = new dbEntities5())
{
keylist = entities.keyart1.Where(e => e.keyword != keyword).ToList();
var result = keylist.Distinct(new ItemEqualityComparer());
return result;
}
}
I think i found the answer if anybody interested
public IEnumerable<keyart1> Get([FromUri] string[] keyword1)
{
List<keyart1> keylist;
List<IEnumerable<keyart1>> ll;
using (dbEntities5 entities = new dbEntities5())
{
ll = new List<IEnumerable<keyart1>>();
foreach (var item in keyword1)
{
keylist = entities.keyart1.Where(e => e.keyword != item).ToList();
var result = keylist.Distinct(new ItemEqualityComparer());
ll.Add(result);
}
var intersection = ll.Aggregate((p, n) => p.Intersect(n).ToList());
return intersection;
}
}

C# Calculate field inside LINQ Query

I need some help to calculate a property inside my Linq query.
I know I need to use "let" somewhere, but I can't figure it out!
So, first I have this method to get my list from Database:
public BindingList<Builders> GetListBuilders()
{
BindingList<Builders> builderList = new BindingList<Builders>();
var ctx = new IWMJEntities();
var query = (from l in ctx.tblBuilders
select new Builders
{
ID = l.BuilderID,
Projeto = l.NomeProjeto,
Status = l.Status,
DataPedido = l.DataPedido,
DataPendente = l.DataPendente,
DataEntregue = l.DataEntregue,
DataAnulado = l.DataAnulado
});
foreach (var list in query)
builderList.Add(list);
return builderList;
}
Then, I have a function to calculate the Days between Dates accordingly to Status:
public int GetDays()
{
int Dias = 0;
foreach (var record in GetListBuilders)
{
if (record.Status == "Recebido")
{
Dias = GetBusinessDays(record.DataPedido, DateTime.Now);
}
else if (record.Status == "Pendente")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataPendente);
}
else if (record.Status == "Entregue")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataEntregue);
}
else if (record.Status == "Anulado")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataAnulado);
}
}
return Dias;
}
I need to call the GetDays in a DataGridView to give the days for each record.
My big problem is, How do I get this? include it in Linq Query? Calling GetDays() (need to pass the ID from each record to GetDays() function)!?
Any help?
Thanks
I think it would be easier to create an extension method:
public static int GetBusinessDays(this Builders builder) // or type of ctx.tblBuilders if not the same
{
if (builder == null) return 0;
switch(builder.status)
{
case "Recebido": return GetBusinessDays(builder.DataPedido, DateTime.Now);
case "Pendente": return GetBusinessDays(builder.DataPedido, (DateTime)builder.DataPendente);
case "Entregue": return GetBusinessDays(builder.DataPedido, (DateTime)builder.DataEntregue);
case "Anulado": GetBusinessDays(builder.DataPedido, (DateTime)builder.DataAnulado);
default: return 0;
}
}
Then, call it like that:
public BindingList<Builders> GetListBuilders()
{
BindingList<Builders> builderList = new BindingList<Builders>();
var ctx = new IWMJEntities();
var query = (from l in ctx.tblBuilders
select new Builders
{
ID = l.BuilderID,
Projeto = l.NomeProjeto,
Status = l.Status,
DataPedido = l.DataPedido,
DataPendente = l.DataPendente,
DataEntregue = l.DataEntregue,
DataAnulado = l.DataAnulado,
Dias = l.GetBusinessDays()
});
foreach (var list in query)
builderList.Add(list);
return builderList;
}
To do better, to convert a object to a new one, you should create a mapper.
Why does it need to be a part of the query? You can't execute C# code on the database. If you want the calculation to be done at the DB you could create a view.
You're query is executed as soon as the IQueryable is enumerated at the foreach loop. Why not just perform the calculation on each item as they are enumerated and set the property when you are adding each item to the list?

get count in linq query

i want to get count in linq query its work fine without comparing date in where condition but after comparing date it gives exception.
public static IList GetAllCategoryData()
{
using (var objEntity = new BlueCouponEntities())
{
return (from TBL in objEntity.CategoryMasters.AsEnumerable()
let IIT = TBL.CategoryImageTransactions
select new
{
TBL.CategoryID,
TBL.CategoryName,
CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > DateTime.Now.Date).Count(),
}
).ToList();
}
}
Error is : The specified type member ;Date; is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
You have to use EntityFunctions.TruncateTime to get the Date part of DateTime
using (var objEntity = new BlueCouponEntities())
{
return (from TBL in objEntity.CategoryMasters.AsEnumerable()
let IIT = TBL.CategoryImageTransactions
select new
{
TBL.CategoryID,
TBL.CategoryName,
CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > EntityFunctions.TruncateTime(DateTime.Now)).Count(),
}
).ToList();
}
Since DateTime.Now is Constant at the moment, you could also write this
using (var objEntity = new BlueCouponEntities())
{
DateTime now = DateTime.Now.Date;
return (from TBL in objEntity.CategoryMasters.AsEnumerable()
let IIT = TBL.CategoryImageTransactions
select new
{
TBL.CategoryID,
TBL.CategoryName,
CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > now).Count(),
}
).ToList();
}
It has nothing to do with the Count() function. As the exception says, its
a DateTime problem. Use DbFunctions.TruncateTime (EntityFunctions.TruncateTime is deprecated since EF6)
public static IList GetAllCategoryData()
{
using (var objEntity = new BlueCouponEntities())
{
return (from TBL in objEntity.CategoryMasters.AsEnumerable()
let IIT = TBL.CategoryImageTransactions
select new
{
TBL.CategoryID,
TBL.CategoryName,
CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && EntityFunctions.TruncateTime(Lg.OfferMaster.EndDate) > EntityFunctions.TruncateTime(DateTime.Now.Date)).Count(),
}
).ToList();
}
}
Add following lines:
var today = DateTime.Now.Date;
Then use today instead of DateTime.Now.Date into linq query.

Method 'System.String GetState(int32)' has no supported translation to SQL

I'm using the below code to fetch the state. I'm getting the error" Method 'System.String GetState(int32)' has no supported translation to SQL".Please let me know where i'm doing a mistake.
public IQueryable<ViewModel> GetResult()
{
IQueryable<ViewModel> result;
if (isDestinationSite)
{
result = (from table1 in this.db.tblTable1
select new ViewModel
{
State= this.GetState(table1.PersonUID),
});
}
private string GetState(int PersonUID)
{
using ( PersonPref pref = new PersonPref ())
{
pref .selectPref(ApplicationCode.MyApp, PersonPref .preference);
if (pref.PesronValue== "True")
{
return "Successfull";
}
else
{
return "Failure";
}
}
}
SQL doesn't know anything about your function so you just need to move it outside of your linq query.
List<ViewModel> result;
var personUID = (from table1 in this.db.tblTable1 select table1.PersonUID).ToList();
foreach (var id in personUID)
{
result.Add(new ViewModel { State = GetState(id) });
}
You can write iterate your query with AsEnumerable and then do the selection like:
result = (from table1 in this.db.tblTable1
.AsEnumerable()
select new ViewModel
{
State= this.GetState(table1.PersonUID),
});

Categories

Resources