I have a table and company_type is one of its columns. Let's say cells look like this:
I want to filter this table by multiple checkboxes and they have a,b,c... values.
#else if
{
if (checkedBoxes.Length == 1)
{
var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) select new Joincco { Companies = check };
}
else if (checkedBoxes.Length == 2)
{
var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) || check.company_type.Contains(checkedBoxes[1]) select new Joincco { Companies = check };
}
else if (checkedBoxes.Length == 3)
{
var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) || check.company_type.Contains(checkedBoxes[1]) || check.company_type.Contains(checkedBoxes[2]) select new Joincco { Companies = check };
}
This code works but is there an easier way?
Related
I cant seen to use ToList(); or take(6) items on this select statement.
I need to select only 6. this is what i have witch works but displays 1 only on the 6 iterations of the repeater.
public string GetImage(string pId)
{
Compras context = new Compras();
Product pr = context.Products.FirstOrDefault();
if (pr != null && pr.Picture != null && pr.Picture.Count() > 0)
{
return "data:image/jpg;base64," + Convert.ToBase64String((pr.Picture));
}
return "data:image/jpg;base64," + Convert.ToBase64String(File.ReadAllBytes(Server.MapPath("~/") + "white.jpg"));
}
I wish i could use as on this next:
var context = new Compras();
var prouctQ = from p in context.Products.Take(6) select new { p.ProductName, p.Picture }; //with projections
var Products = prouctQ.ToList();
if (Products.Count > 0)
Please make sure that you have "using System.Linq" at the top of the code file.
List<search> alllist = wsWSemloyee.GetAllProject(); //where search is model class contains properties..
string search_key = "%" + txtsearch.Text.Trim() + "%";
List<search> result = new List<search>();
foreach (search item in alllist)
{
var op = (
from a in alllist
where a.Sfirstname.Contains(search_key) || a.Slastname.Contains(search_key) || a.Smob.Contains(search_key) || a.Scity.Contains(search_key) || a.Sstate.Contains(search_key)
//where SqlMethods.Like(a.Sfirstname,search_key)||SqlMethods.Like(a.Slastname,search_key)||SqlMethods.Like(a.Scity,search_key)||SqlMethods.Like(a.Smob,search_key)||SqlMethods.Like(a.Sstate,search_key)
select a
);
// List<search> lst = op.ToList<search>();
if (op != null)
{
result.Add(item);
}
}
if (result.Count != 0)
{
dgv_searchreport.DataSource = result;
dgv_searchreport.DataBind();// data grid view
}
its not working...
giving all result present in alllist..
//where search is model class contains properties..
I'ts because you are comparing if result of your linq query is not null and then adding variable from foreach clause. When any single item from allproducts will match condition then op will be never null and then whole collection will be contained in result. What you want is probably following:
var result = (from a in alllist
where a.Sfirstname.Contains(search_key)
|| a.Slastname.Contains(search_key)
|| a.Smob.Contains(search_key)
|| a.Scity.Contains(search_key)
|| a.Sstate.Contains(search_key)
select a).ToList();
That will pick all items which match condition and enumerate them to list.
May this helps you..
string search_key = txtsearch.Text.Trim(); // instead "%" + txtsearch.Text.Trim() + "%";
List<search> result = new List<search>();
var op = (from a in alllist
where a.Sfirstname.Contains(search_key) || a.Slastname.Contains(search_key) || ......
select a);
if(op.Count() > 0)
result = op.ToList();
I'm trying to insert only males teachers into the "MaleTeachers" table, but after program is executed I see only one teacher in that table. In addition, I have more then one teacher in the "Stuffs" table, but inserted one is the last that matches "if" criteria. Could you correct this code please. Service implementation:
public void AddTeachers()
{
DataClasses1DataContext data = new DataClasses1DataContext();
DataClasses2DataContext data2 = new DataClasses2DataContext();
MaleTeacher tchr = new MaleTeacher();
foreach (var d in data.Stuffs)
{
if (d.stuffSex == true && d.stuffJob == "Teacher")
{
tchr.teacherName = d.stuffName;
tchr.teacherAge = d.stuffAge;
tchr.teacherJob = d.stuffJob;
tchr.teacherDepartm = "geology";
data2.MaleTeachers.InsertOnSubmit(tchr);
}
}
data2.SubmitChanges();
}
you foreach loop should be.
foreach (var d in data.Stuffs)
{
if (d.stuffSex == true && d.stuffJob == "Teacher")
{
MaleTeacher tchr = new MaleTeacher();
tchr.teacherName = d.stuffName;
tchr.teacherAge = d.stuffAge;
tchr.teacherJob = d.stuffJob;
tchr.teacherDepartm = "geology";
data2.MaleTeachers.InsertOnSubmit(tchr);
}
}
You are creating only one intance and then modifying it again and again... instead you should create a different MaleTeacher instance on every time.
MaleTeacher tchr = new MaleTeacher();
foreach (var d in data.Stuffs)
{
if (d.stuffSex == true && d.stuffJob == "Teacher")
{
tchr.teacherName = d.stuffName;
tchr.teacherAge = d.stuffAge;
tchr.teacherJob = d.stuffJob;
tchr.teacherDepartm = "geology";
data2.MaleTeachers.InsertOnSubmit(tchr);
tchr = new MaleTeacher();
}
}
I Have to check and add the optional parameter in function but its taking lengthy code to go through IF-Else statement, If I choose switch statement then Cannot convert 'var' variable to string error keep coming up, How do I check and add optional parameters to linq query please help. Here is my code. (I will provide both the one with If statement and other one with switch statement which is throwing error)
Code 1 If-else statement:
public static void loadGrid(ref GridView gvMain, string cID, string desig = "All", string importancy = "All", string status = "All")
{
int _cId = Convert.ToInt32(cID);
List<clsclass> list = new List<clsclass>();
var db = new MyEntities();
if (_cId == 0 && desig == "All" && importancy == "All" && status == "All")
{
var query = from table in db.Members select table;
list.Clear();
foreach (var item in query)
{
clsclass ctl = new clsclass();
ctl.Id = Convert.ToInt32(item.LID);
ctl.Name = item.FirstName + " " + item.LastName;
ctl.Gender = item.Gender;
ctl.Age = Convert.ToInt32(item.Age);
ctl.Mobile = item.Mobile;
ctl.Workphone = item.WorkPhone;
ctl.Designation = item.Designation;
ctl.Importancy = item.Importancy;
list.Add(ctl);
}
}
else if (_cId != 0 && desig == "All" && importancy == "All" && status == "All")
{
var query = from table in db.Members where table.CID == _cId select table;
list.Clear();
foreach (var item in query)
{
clsclass ctl = new clsclass();
ctl.Id = Convert.ToInt32(item.LID);
ctl.Name = item.FirstName + " " + item.LastName;
ctl.Gender = item.Gender;
ctl.Age = Convert.ToInt32(item.Age);
ctl.Mobile = item.Mobile;
ctl.Workphone = item.WorkPhone;
ctl.Designation = item.Designation;
ctl.Importancy = item.Importancy;
list.Add(ctl);
}
}
//AND SO ON I HAVE TO CHECK THE OPTIONAL PARAMETERS......
//else if()
//{
//}
}
And In below code If I try to use switch statement to bind query based condition its throwing error:
Code 2:Switch statement:
public static void LoadGrid(ref GridView gvMain, string cID, string desig = "All", string importancy = "All", string status = "All")
{
int _cId = Convert.ToInt32(cID);
List<clsclass> list = new List<clsclass>();
var db = new MyEntities();
var query;
switch (query)
{
case _cId == 0 && desig == "All" && importancy == "All" && satus == "All":
query = from b in db.ConstituencyLeaders select b;
case _cId != 0 && desig == "All" && importancy == "All" && satus == "All":
query = from b in db.ConstituencyLeaders where b.ConstituencyID == _cId select b;
}
foreach (var item in query)
{
clsclass cl = new clsclass();
cl.LeaderId = item.LID;
//...remaining members add
list.Add(cl);
}
gvMain.DataSource = list;
gvMain.DataBind();
}
So basically I got two questions How to shorten the codes to capture the optional parameters if switch statement is better option then how would I achieve var query from Case:
any help much appreciated.
What you can do is.
var query = db.Members.AsQuerryable();
if(_cid != "")
{
query = query.where(table => table.CID == _cId);
}
Then use that in your statement
var result = from table in query where table.CID == _cId select table;
or we also used to do or statements.
var query= from table in query where (table.CID == _cId || _cId = "") select table;
so if the value is empty it just goes through or if there is a value it checks.
What would be the best practice for setting a status depending on several other "columns" retrieved in a linq query.
var result = (from q in query
select new Item
{
ApprovedDate = q.ApprovedDate,
CreatedDate = q.CreatedDate,
DeclinedDate = q.DeclinedDate,
Status = 0
});
I'd like to set the status to either 0, 1, 2.
(ApprovedDate == null and DeclinedDate == null) --> 0
(ApprovedDate != null and DeclinedDate == null) --> 1
(DeclinedDate != null) --> 3
So perhaps something like:
var result = (from q in query
select new Item
{
ApprovedDate = q.ApprovedDate,
CreatedDate = q.CreatedDate,
DeclinedDate = q.DeclinedDate,
Status = (q.CreatedDate == null && q.DeclinedDate == null) ? 0 : (q.ApprovedDate != null && q.DeclinedDate == null) ? 1 : 2
});
I might add even more status combinations, so should I try and do this in the linq select query, in my repository object.. Or later on in the controller where I would do a .ToList() and then foreach the list to set the correct status code?
Having even more than 3 statuscodes, the linq query gets "hard" to read.
What about moving status calculation to Item class? If status property depends on other properties value, then it's definitely calculated property:
var result = from q in query
select new Item
{
ApprovedDate = q.ApprovedDate,
CreatedDate = q.CreatedDate,
DeclinedDate = q.DeclinedDate
});
And
public class Item
{
// other properties
public int Status
{
get
{
if (ApprovedDate == null and DeclinedDate == null)
return 0;
if (ApprovedDate != null and DeclinedDate == null)
return 1;
if (DeclinedDate != null)
return 3;
// etc
}
}
}
Actually I think it's best option, because in this case status calculation logic will be close to required data. If (for some reason) you can't use this approach, then move setting statuses to local items collection:
var items = result.ToList().ForEach(i => i.Status = CalculateStatus(i));
Maybe wrapped all in a function An do a linq like this
var result = (from q in query sele q).AsEnumerable()
.Select( x => new Item()
{
ApprovedDate = x.ApprovedDate,
CreatedDate = x.CreatedDate,
DeclinedDate = x.DeclinedDate,
Status = MyStatusFunction(x.CreatedDate,q.DeclinedDate)
});
public int MyStatusFunction(DateTime ApprovedDate , Datetime DeclinedDate)
{
if (ApprovedDate == null and DeclinedDate == null) return 0;
else if(ApprovedDate != null and DeclinedDate == null) return 1;
else if (DeclinedDate != null) return 3;
}