How to convert SqlDataReader to LINQ way? - c#

I wonder how to convert SqlDataReader to LINQ way?
Here is my SqlDataReader code.
string strConn = "server=xxx.com;database=mydb;User ID=test;Password=test;Trusted_Connection=true;";
SqlConnection myConn = new SqlConnection(strConn);
myConn.Open();
string strSQL = "select period from timetable_view where identity_num = '" + Identity_NUM + "' week = '3'";
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
SqlDataReader myDataReader = myCommand.ExecuteReader();
int Count = Add_CourseConfirmedQuery.Count();
Random rnum = new Random();
string[] arr = new string[Count];
for (int i = 0; i < Count; i++)
{
myDataReader.Read();
arr[i] = myDataReader["period"].ToString();
}
ViewBag.test = arr[0];
ViewBag.test2 = arr[1];
myCommand.Cancel();
myDataReader.Close();
myConn.Close();
myConn.Dispose();
string[] input2 = new string[Count];
for (int i = 0; i < Count; i++)
{
input2[i] = arr[i];
}
This code works fine.
I've tried to code in LINQ but it doesn't work.
Here's the LINQ code that I've tried, but I have no idea how to extract all records of a.identity_num, and put them into an array like the code above(SqlDataReader).
var test = from a in timetable_view
where a.identity_num = Identity_NUM && a.week = "3"
select a new{a.identity_num};
ViewBag.test = test.FirstOrDefault();
[UPDATE Question]
This is what I am trying now.
I can't extract the right records from my table.
But the page display: System.String[]
var Query = from m in db.members
join d in db.departments on m.department equals d.department_id
join s in db.select_list on m.member_id equals s.member_id
join c in db.courses on s.kkk_id equals c.kkk_id
join t in db.teachers on c.teacher equals t.teacher_id
where m.identity_num == Identity_NUM && c.week == "3"
select c.period;
var PA = Query.ToArray();
int Count = Query.Count();
string[] arr = new string[Count];
for (int i = 0; i < Count; i++)
{
arr[i] = PA.ToString();
}
ViewBag.test = arr[0];
ViewBag.test2 = arr[1];
.............
............
...........
string[] input2 = new string[Count];
for (int i = 0; i < Count; i++)
{
input2[i] = arr[i];
}
.............
............
...........

Updated to match changed question:
Don't select a new anonymous object, just select the value:
var arr= (from a in timetable_view
where a.identity_num = Identity_NUM && a.week = "3"
select a.period).ToArray();
Fully updated change should be
var Query = from m in db.members
join d in db.departments on m.department equals d.department_id
join s in db.select_list on m.member_id equals s.member_id
join c in db.courses on s.kkk_id equals c.kkk_id
join t in db.teachers on c.teacher equals t.teacher_id
where m.identity_num == Identity_NUM && c.week == "3"
select c.period;
var arr = Query.ToArray();
ViewBag.test = arr[0];
ViewBag.test2 = arr[1];
From the comments:
The error message generated by having ToString() in the code indicates to us that period is a string anyhow and so the call can be removed.
To get count, int Count = arr.Length
The for-loop has been removed because it is redundant, using the ToArray() function achieves the same result.

you should need to convert linkq to toArray:
var TEST = (from a in timetable_view
where a.identity_num = Identity_NUM && a.week = "3"
select a new{a.identity_num}).ToArray();
var Query = from m in db.members
join d in db.departments on m.department equals d.department_id
join s in db.select_list on m.member_id equals s.member_id
join c in db.courses on s.kkk_id equals c.kkk_id
join t in db.teachers on c.teacher equals t.teacher_id
where m.identity_num == Identity_NUM && c.week == "3"
select c.period.ToString();
var arr = Query.ToArray();
ViewBag.test = arr[0];
ViewBag.test2 = arr[1];

You need to convert linq query to array. Bellow code should do this:
var test = (from a in school_timetable_view
where a.identity_num == Identity_NUM && a.week == "3"
select a new{a.identity_num}).ToArray();

Related

Entity Framework no statements executed after query

So i'm using Quartz to create a task scheduler for my program and I'm having issues where if there are multiple jobs to run, it will repeatedly execute the query for the respective job but then never exectues the very next line. It's as if it hangs as soon as i hit tolist(). Any ideas?
try
{
//work on query further , need to get client ID correctly
if (vehicleses.Count == 0)
return null;
string siteId = QueryExportSiteWithId(exportSiteId).SiteId;
string clientId = vehicleses[0].ClientID;
db.Database.Log = Console.Write;
var inventoryyReturn = from i in db.Inventory_Vehicles
where dealerIdList.Any(c => c == i.ClientID) && i.Archived != "1" && i.Holding != "1" &&
i.Status == "A"
select i;
var inventoryDescription = from i in db.Inventory_Descriptions
where
inventoryyReturn.Any(
c => new {client = c.ClientID, inv = c.ID} == new {client = i.ClientID, inv = i.InventoryID})
select i;
var settingsExports = from i in db.Settings_Exports
where inventoryyReturn.Any(c => c.ClientID == i.ClientID)
select i;
var settingLots = from i in db.Settings_Lots
where
inventoryyReturn.Any(
c => new {client = c.ClientID, lot = c.LotID} == new {client = i.ClientID, lot = i.ID})
select i;
var inventoryFeatures = from i in db.Inventory_Features
where
inventoryyReturn.Any(
c => new {client = c.ClientID, inv = c.ID} == new {client = i.ClientID, inv = i.InventoryID})
select i;
var inventoryPhotos = from i in db.Inventory_Photos
where
inventoryyReturn.Any(c => c.ID == i.InventoryID)
select i;
var longReturnListt = (from i in inventoryyReturn
join l in inventoryDescription on new {inv = i.ID, cli = i.ClientID} equals
new {inv = l.InventoryID, cli = l.ClientID} into descGroup
from m in descGroup.DefaultIfEmpty()
join s in settingsExports on i.ClientID equals s.ClientID into settingGroup
from sg in settingGroup.DefaultIfEmpty()
join sl in settingLots on new {client = sg.ClientID, lot = sg.LotID} equals
new {client = sl.ClientID, lot = sl.ID} into lotsGroup
from lg in lotsGroup.DefaultIfEmpty()
join se in db.Settings_ExportSites on new {client = lg.ClientID, lotId = i.LotID, site = siteId}
equals new {client = se.ClientID, lotId = se.LotID, site = se.Site} into exportGroup
from eg in exportGroup.DefaultIfEmpty()
join f in inventoryFeatures on new {inv = i.ID, cli = i.ClientID} equals
new {inv = f.InventoryID, cli = f.ClientID} into invFeatGroup
from ifg in invFeatGroup.DefaultIfEmpty()
join p in inventoryPhotos on i.ID equals p.InventoryID into photo
from photos in photo.DefaultIfEmpty()
orderby i.ID
select new {i, m, sg, photoo = photo.ToList(), lg, ifg, eg}
into grouped
group grouped by new {grouped.i.ClientID}
into groupedDone
//select groupedDone
from categories in groupedDone
select new NewType
{
InventoryVehicles = categories.i,
InventoryDescriptions = categories.m,
SettingsExports = categories.sg,
InventoryPhotos = categories.photoo,
SettingsLots = categories.lg,
InventoryFeatures = categories.ifg,
SettingsExportSites = categories.eg
}
).ToList();
// var sql = ((System.Data.Entity.Core.Objects.ObjectQuery) longReturnListt as ObjectQuery);
// var trace = sql.ToTraceString();
if (longReturnListt != null)
{
//returnList.AddRange(longReturnListt.);
return returnList;
}
return null;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}

How to use LINQ to select the object with the smaller value of the property and its value directly

var req = (from k in dc.operations.ToList()
group k by k.id_employee into g
select new { id_emp = g.Key , nbr = g.Count(), }
).Take(1).SingleOrDefault();
double mint=0;
for (int i = 0; i < req.nbr; i++)
{
var r = (from l in dc.operations
where l.id_employee == req.id_emp
select l).Take(1).ToList();
var r2 = (from l in dc.operations
where l.id_employee == req.id_emp
&& l.date_operation.Value > r[i].date_operation.Value
select l).Take(1).ToList();
double nbr_minut = (r[i].date_operation.Value - r2[i].date_operation.Value).TotalMinutes;
mint = +nbr_minut;
nbr_minut = 0;
}
TimeSpan span = TimeSpan.FromMinutes(mint);
string nbr_houre = span.ToString(#"hh\:mm");
label1.Text = nbr_houre.ToString();
To simplify the question, lets say you have a list of Person and you want to get the youngest person and his age.
You can do this:
people.OrderBy(p => p.Age).Select(p => new {Dude = p, Age = p.Age}).FirstOrDefault();

Not getting the difference between two list by using linq

I have two lists as follows:
var SeparatedEmployees = (from s in DataContext.HRM_EMP_TRMN.AsEnumerable()
where s.TRMN_FINL_STUS == "SA" && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on s.EMP_CODE equals e.EMP_CODE
where e.ACTIVE_STATUS == "A"
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
var ConfirmedEmployees = (from c in DataContext.HRM_EMP_FINL_STMT_MST.AsEnumerable()
where ((Convert.ToDateTime(c.FINL_STMT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(c.FINL_STMT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on c.EMP_CODE equals e.EMP_CODE
join s in DataContext.HRM_EMP_TRMN on c.EMP_CODE equals s.EMP_CODE
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
Tyring to remove the items from the first list, which are also in second list.
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ConfirmedEmployees.Contains(item)
select item).ToList();
Tried this one too:
FinalSeparatedEmployees = SeparatedEmployees.Except(ConfirmedEmployees).ToList<HRM_EMP_FINL_STMT_MSTModel>();
But not getting the accurate result. What I'm missing? Thanks.
Its better to use EMP_CODE because your objects are not comparable.
var ids = ConfirmedEmployees.Select(x => x.EMP_CODE).ToList();
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ids.Contains(item.EMP_CODE)
select item).ToList();

Group the result using linq

I have some problems and don't know what to do, can someone help me please?
I have a table like that:
ID Name Produkt Comment aa bb
1 Mike AA YY x
1 Mike AA YY x
I want to group with linq the result like to have Mike but just in one line
1 Mike AA YY x x
My code:
var results = from t1 in table.AsEnumerable()
join tb2 in table2.AsEnumerable()
on t1.Field<string>("Name") equals tb2.Field<string>("Name") into prodGroup
from table4 in prodGroup.DefaultIfEmpty()
select new
{
ID = t1.Field<Int32?>("ID"),
Name = t1.Field<String>("Name"),
Produkt = t1.Field<String>("Produkt"),
Attribute = t1.Field<String>("Attribute"),
Comment = table4 != null ? table4.Field<String>("Comment") : null,
};
foreach (var r in results)
{
var productIndex = result.Columns.IndexOf(r.Attribute);
var vals = new List<object>() { r.ID, r.Name, r.Produkt, r.Comment };
for (int i = 4; i < result.Columns.Count; i++)
{
if (i == productIndex)
{
vals.Add(true);
}
else
{
vals.Add(false);
}
}
result.LoadDataRow(vals.ToArray(), true);
}
Try this:
var result = from t1 in table.AsEnumerable()
group t1 by t1.Name into t1group
select new
{
Name = t1group.FirstOrDefault().Name
,ID = t1group.FirstOrDefault().ID
,Product = t1group.FirstOrDefault().Product
,Comment = t1group.FirstOrDefault().Comment
,aa = (t1group.Select(x => x.aa??"" + x.bb??"")).Aggregate((a, b) => (a + ", " + b))
};

Join LINQ with a List<> in select new

hi first time im asking here so il try to do it correctly
i have a problem im making a shopping basket and im nearly there but always a but
what i want to have is something like this
List<HKurv> KurvInnhold = (List<HKurv>)Session["KurvInnhold"];
DataClasses1DataContext db = new DataClasses1DataContext();
if (Session["KurvInnhold"] != null)
{
var query = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
d.VareKjøpt.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
BestiltAntall = d.AntallValgt,
Price = b.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query;
Handlekurv1.DataBind();
}
But it does not allow for usage of db and list<> in same query
Solved! Modified magnus's answer
var kjopKollonne = from p in KurvInnhold
select p.VareKjøpt;
var query1 = (from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
where
kjopKollonne.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}).ToList();
var query2 = from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();
Try this:
var query1 = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
KurvInnhold.Select(k => k.VareKjøpt).Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}.ToList();
var query2 =
from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();

Categories