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.
Related
I'm trying to get a DataRow from a dtResult datatable if column name in [colName] list has a matching value as [grbByValue] list. my goal in the below code is to get [test1] and [test2] return datarow from dtResult and should be the same as [update] (which is hard coded). but have issue in both test1 & test2. test1 has error and don't know how fix and test2 is returning null.
rule is a DataTable that looks like this:
All the below logic is run for each row of rule.
dtResult is also a DataTable that looks like this:
EDITED CODE
string[] grpby = { "ageband","gender","code"};
List<string> grbByValue = new List<string>() { "1","85+","1","1010"};
DataTable dtResult = new DataTable();
DataColumn dc = dtResult.Columns.Add("id", typeof(int));
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dtResult.Columns.Add("DataSourceID");
dtResult.Columns["DataSourceID"].DefaultValue = "1";
dtResult.Columns.Add("RuleID");
dtResult.Columns.Add("GroupBy0");
dtResult.Columns.Add("GroupBy1");
dtResult.Columns.Add("GroupBy2");
dtResult.Columns.Add("GroupBy3");
dtResult.Columns.Add("GroupBy4");
dtResult.Columns.Add("GroupBy5");
dtResult.Columns.Add("Result", typeof(decimal));
dtResult.Columns["Result"].DefaultValue = 0.00;
var colName = (from a in dtResult.Columns.Cast<DataColumn>()
where a.ColumnName.ToString().StartsWith("GroupBy")
select a.ColumnName).OrderBy(x => x).ToList();
colName.Insert(0, "RuleID");
colName = colName.GetRange(0, grbByValue.Count);
//comment/UNCOMMENT below to test [test1]
//DataRow z = dtResult.NewRow();
//for (int i = 0; i < grbByValue.Count; i++)
//{
// z[colName[i]] = grbByValue[i];
//}
//dtResult.Rows.Add(z.ItemArray);
var distDtResult = dtResult.DefaultView.ToTable(true, colName.ToArray());
bool exist = false;
DataRow update = null;
foreach (DataRow dr in distDtResult.Rows)
{
var row = dr.ItemArray.ToList();
exist = row.SequenceEqual(grbByValue);
if (exist == true)
{
//var test1 = (from t1 in distDtResult.AsEnumerable().Where(r => r.ItemArray == dr.ItemArray)
// join t2 in (from m in dtResult.AsEnumerable()
// select new
// {
// //ideally the below column list will be derived from [colName] dynamically
// RuleID = m.Field<string>("RuleID"),
// GroupBy0 = m.Field<string>("GroupBy0"),
// GroupBy1 = m.Field<string>("GroupBy1"),
// GroupBy2 = m.Field<string>("GroupBy2")
// }) on t1.ItemArray equals t2.ItemArray
// select new
// {
// t2
// }).FirstOrDefault();
update = dtResult.AsEnumerable().Where(r =>
r.Field<int>("id") == 1 &&
r.Field<string>("DataSourceID") == "1" &&
r.Field<string>("RuleID") == "1" &&
r.Field<string>("GroupBy0") == "85+" &&
r.Field<string>("GroupBy1") == "1" &&
r.Field<string>("GroupBy2") == "1010").FirstOrDefault();
break;
}
}
if (exist == false)
{
DataRow a = dtResult.NewRow();
for (int i = 0; i < grbByValue.Count; i++)
{
a[colName[i]] = grbByValue[i];
}
dtResult.Rows.Add(a.ItemArray);
var test2 = dtResult.AsEnumerable().Where(r => r.ItemArray.Equals(a.ItemArray)).FirstOrDefault();
update = dtResult.AsEnumerable().Where(r =>
r.Field<int>("id") == 1 &&
r.Field<string>("DataSourceID") == "1" &&
r.Field<string>("RuleID") == "1" &&
r.Field<string>("GroupBy0") == "85+" &&
r.Field<string>("GroupBy1") == "1" &&
r.Field<string>("GroupBy2") == "1010").FirstOrDefault();
}
This might be a good starting point, at least to better ask questions and move towards an answer.
string[] colName = { "RuleID", "GroupBy0", "GroupBy1", "GroupBy2" };
// "All the below logic is run for each row of rule"
// this goes through each row of the rule DataTable
foreach (DataRow rule in ruleTable.Rows)
{
// This is going to be equivalent to the grpby variable you specified
var groupRules = rule.Field<string>("GroupBy").ToString().Split("|");
// Some sort of mapping may need to go here to go from "ageband" to "GroupBy0", "gender" to "GroupBy1", etc.
foreach(DataRow row in dtResult.Rows)
{
DataTable distDtResult = dtResult.DefaultView.ToTable(true, colName);
var updateTEST = from dr in distDtResult.AsEnumerable()
where dr.Field<string>("RuleID") == rule["RuleID"].ToString()
&& dr.Field<string>("GroupBy0") == row["GroupBy0"].ToString() // ageband
&& dr.Field<string>("GroupBy1") == row["GroupBy1"].ToString() // gender
&& dr.Field<string>("GroupBy2") == row["GroupBy2"].ToString() // code
// more
select dr;
}
}
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 want to update table but its not working
Here is the code:
public Boolean setSectionTickSign(decimal Trans_ID, decimal Job_ID, string SectioName)
{
string sectionames = "";
Transcription_Master Trans_Mastr = new Transcription_Master();
try
{
var Trans_Master = (from Trans_Mast in r2ge.Transcription_Master where Trans_Mast.Transcription_Id == Trans_ID && Trans_Mast.Entity_Id == Job_ID select new
{
Trans_Mast.Completed_Trans_Sections
}).Distinct().ToList();
var complt_trans = Trans_Master.AsEnumerable().Where(dr = > dr.Completed_Trans_Sections != null).ToList();
if (complt_trans.Count == 0)
{
if (sectionames == "")
{
Trans_Mastr.Completed_Trans_Sections = SectioName;
}
}
else
{
Trans_Mastr.Completed_Trans_Sections = "," + SectioName;
}
int sc = r2ge.SaveChanges();
}
}
It does not update database..what is wrong in it??
You should change this piece of code to such a thing:
var Trans_Master = (from Trans_Mast in r2ge.Transcription_Master
where Trans_Mast.Transcription_Id == Trans_ID
&& Trans_Mast.Entity_Id == Job_ID
select Trans_Mast).Distinct().ToList();
In this case Your variable Trans_Maser will be refference to object from collection, so changes will be done on object taken from EF context, and SaveChanges will give correct result.
Solved my own problem Transcription_Master Trans_Mastr = new Transcription_Master(); no need to create new object
public Boolean setSectionTickSign(decimal Trans_ID, decimal Job_ID, string SectioName)
{
string sectionames = "";
try
{
var empQuery = r2ge.Transcription_Master.Where(l => l.Transcription_Id == Trans_ID && l.Entity_Id == Job_ID).ToList();
foreach (Transcription_Master Trans_Mastrr in empQuery)
{
if (empQuery.Count == 0)
{
if (sectionames == "")
{
Trans_Mastrr.Completed_Trans_Sections = SectioName;
}
}
else
{
Trans_Mastrr.Completed_Trans_Sections = Trans_Mastrr.Completed_Trans_Sections + "," + SectioName;
}
}
int sc = r2ge.SaveChanges();
}
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;
}
Right, bit of a strange question; I have been doing some linq to XML work recently (see my other recent posts here and here).
Basically, I want to be able to create a query that checks whether a textbox is null before it's value is included in the query, like so:
XDocument db = XDocument.Load(xmlPath);
var query = (from vals in db.Descendants("Customer")
where (if(textbox1.Text != "") {vals.Element("CustomerID") == Convert.ToInt32(textbox1.Text) } ||
if(textbox2.Text != "") {vals.Element("Name") == textbox2.Text})
select vals).ToList();
Just use the normal Boolean operators && and ||:
XDocument db = XDocument.Load(xmlPath);
var query = (from vals in db.Descendants("Customer")
where (textbox1.Text != "" &&
vals.Element("CustomerID") == Convert.ToInt32(textbox1.Text)) ||
(textbox2.Text != "" && vals.Element("Name") == textbox2.Text)
select vals).ToList();
That's just a direct translation of the original code - but I think you'll want a cast from vals.Element("CustomerID") to int, and you don't really want to convert textbox1.Text on every iteration, I'm sure. You also need to convert the "name" XElement to a string. How about this:
int? customerId = null;
if (textbox1.Text != "")
{
customerId = int.Parse(textbox1.Text);
}
XDocument db = XDocument.Load(xmlPath);
var query = (from vals in db.Descendants("Customer")
where (customerId != null &&
(int) vals.Element("CustomerID") == customerId) ||
(textbox2.Text != "" &&
(string) vals.Element("Name") == textbox2.Text)
select vals).ToList();
Alternatively, you could separate out the two parts of the query and "union" the results together. Or - preferably IMO - you could build the query more dynamically:
var query = db.Descendants("Customer");
if (textbox1.Text != null)
{
int customerId = int.Parse(textbox1.Text);
query = query.Where(x => (int) x.Element("CustomerID") == customerId);
}
if (textbox2.Text != null)
{
query = query.Where(x => (string) x.Element("Name") == textbox2.Text);
}
List<XElement> results = query.ToList();