Is there any way get datarow from datatable without using foreach - asp.net-mvc

Controller
foreach (DataRow temp in act.Rows)
{
_oResolutionModel.activityNo = temp["ActivityID"].ToString();
_oResolutionModel.assignTechnician = temp["TechNo"].ToString();
_oResolutionModel.recommendation = temp["RECOMMENDATION"].ToString();
_oResolutionModel.jobStart = (DateTime)temp["JobStart"];
_oResolutionModel.jobEnd = (DateTime)temp["JobEnd"];
_oResolutionFacade.setResolutionID(_oResolutionModel.activityNo);
DataTable res = _oResolutionFacade.getResolution(_oAppSetting.ConnectionString);
foreach (DataRow x in res.Rows)
{
_oResolutionModel.solution = x["Resolution"].ToString();
_oResolutionModel.remarks = x["Remarks"].ToString();
_oResolutionList.Add(_oResolutionModel);
break;
}
_oResolutionList.Add(_oResolutionModel);
break;
}
In here my _oResolutionList count = 1, meaning there's two data in it and it duplicated the first data. I want to have only 1 data in my _oResolutionList. Do I need to add some code in my inner Foreach or should I change something on it.?
Or You can suggest me how to delete the second data entry.?

Instead of using a foreach loop. You can also check the nullity first and then assign.
You can also do :
_oResolutionFacade.setResolutionID(_oResolutionModel.activityNo);
DataTable res = _oResolutionFacade.getResolution(_oAppSetting.ConnectionString);
_oResolutionModel.solution = res.Rows[0]["Resolution"].ToString() ?? string.Empty; //To make sure that if it is null it will assign to an empty string
_oResolutionModel.remarks = res.Rows[0]["Remarks"].ToString()?? string.Empty;
You have many solutions to deal with that.
Hope it will help you

Related

How do I remove the foreach from this linq code?

I'm fairly new at MVC and linq and viewmodels in particular. I managed to get a create and index views to work. The "insert" wasn't as hard as the "list".
I have this linq query:
public ActionResult Index()
{
List<BlendElVM> BEVM = new List<BlendElVM>();
var list = (from Blend in db.blends
join BlendEl in db.blendEl on Blend.ID equals BlendEl.ID
select new
{
Blend.ID, Blend.Title, Blend.TransDt, BlendEl.Comment
}).ToList();
foreach (var item in list)
{
BlendElVM o = new BlendElVM(); // ViewModel
o.Comment = item.Comment;
o.Title = item.Title;
o.TransDt = item.TransDt;
o.ID = item.ID;
BEVM.Add(o);
}
return View(BEVM);
}
What I'm not sure about is the "foreach" section. When I'm running in debug, the "list" shows up fine, but if I comment out the "foreach" I get an error - ie not expecting the model. What does the foreach do? It has to do with the database, but I don't understand the where it is using the "o" and setting the columns. I thought it would all be in one linq query. Is it possible to combine the two and eliminate the "foreach"?
var BEVM = (from blend in db.blends
join BlendEl in db.blendEl on Blend.ID equals BlendEl.ID
select new BlendELVM
{
ID = blend.ID,
Title = blend.Title,
TransDT = blend.TransDt,
comment = blendEl.Comment
}).ToList();
I believe that the foreach is needed in order to read every element in the object so in this case you have:
BlendElVM o = new BlendElVM();
So you're creating and object named " o " of the type BlendELVM and this object contains all the attributes that you declared before which are: ID, Title, TransDT, etc
When you put:
foreach (var item in list)
{
BlendElVM o = new BlendElVM(); // ViewModel
o.Comment = item.Comment;
o.Title = item.Title;
o.TransDt = item.TransDt;
o.ID = item.ID;
BEVM.Add(o);
}
You're assigning to the new object o the item that you're reading in the list and in the end adding it to the BVEM list and answering if you can combine them i will say no because at first you're declaring the query and then you're reading the items on the list and assining them to the BEVM list

there's something wrong with my controller codes

My Controller
public ActionResult Index()
{
TechnicianFacade _oTechFacade = new TechnicianFacade();
Maintenance_.Models.IndexModel _oTechModel = new Maintenance_.Models.IndexModel();
IList<Maintenance_.Models.IndexModel> _otechList = new List<Maintenance_.Models.IndexModel>();
var tech = _oTechFacade.getTechnicians("", _oAppSetting.ConnectionString).ToArray();
foreach (var test in tech)
{
string fName = test.GetType().GetProperty("FIRSTNAME").GetValue(test, null).ToString();
_oTechModel.firstName = fName;
_otechList.Add(_oTechModel); <===
}
_oTechModel.fNameList = _otechList;
return View("Index", _oTechModel);
}
In my controller: index, can get all data object from my database. But if I have more than one data object in my database the: _otechList.Add(_otechModel) will overwrite the first entry with the newly added data, like for example lets just say we have 2 object data: (FIRST loop of foreach) _otechList.Add(_oTechModel) has a data of "FIRSTNAME" = "GEM" where count = 0, (SECOND loop of foreach) _otechList.Add(_oTechModel) has a data of "FIRSTNAME" = "DIAMOND" where count = 1, this time the value of count[0] became "FIRSTNAME" = "DIAMOND" as well. Is there something missing in my code or there's something wrong on it?
It will replace because same object value is changed, you need to instantiate object inside foreach loop.
Maintenance_.Models.IndexModel _oTechModel = new Maintenance_.Models.IndexModel();
like this:
foreach (var test in tech)
{
string fName = test.GetType().GetProperty("FIRSTNAME").GetValue(test, null).ToString();
Maintenance_.Models.IndexModel _oTechModel = new Maintenance_.Models.IndexModel();
_oTechModel.firstName = fName;
_otechList.Add(_oTechModel);
}
your object is global so every time same object is added in the list, instantiate it inside foreach loop so that every time new object is added in the list.

LINQ Union Allways returning empty sets

I'm doing some LINQ to look for keywords typed in a textbox. Each keyword ends with ";" and i need to look for itens that contain at least one of those keys.
I thought that i would be able to achieve this with this loop
IEnumerable<ItemFAQ> allResults = null;
foreach (var item in termosPesquisaIsolados)
{
IEnumerable<ItemFAQ> tempResults =
_dbHelpDesk.ItemFAQ
.Where(x => x.DescricaoResposta.Contains(item) || x.TituloTopico.Contains(item))
.ToList()
.Select(x => new ItemFAQ
{
IdPergunta = x.IdPergunta,
TituloTopico = x.TituloTopico,
DescricaoResposta = x.DescricaoResposta.Substring(0, 100)
});
if (allResults != null)
allResults = allResults.Union(tempResults);
else
allResults = tempResults;
}
At first iteration tempResult returns in a test 3 elements then it passes then to allResult, everything ok with that.
The second iteration, tempResult returns 2 ocurrences... then according to code allResult should receive the Union of AllResult and the TempResults, but no matter what i do, when i use the Union clause the result in an Empty Set.
So 3 + 2 = 0 at the end after using Union.
Do you guys can see the mistake at this peace of code or know some issues that could lead to this error ?
Thanks for your time.
try replacing this line:
allResults = allResults.Union(tempResults);
with:
allResults = allResults.Union(tempResults).ToList();

Where on a List/Table in a Query

How can I do a where in a query on a list or table ?
To explain, I have a multiselect listbox where the user can select one or many values which are passed to my action. After that, I get all this values in a list and I want to do a Where on it like that :
List<string> CondCR = new List<string>();
foreach (var testCR in SubCR)
{
CondCR.Add(testCR);
}
ViewBag.CondCR = CondCR;
var query = (from i in items
where i.Field<String>("TIMING").Contains(GetTIMING) && i.Field<String>("CD_CR").Equals(CondCR)
select new Suivi{CD_CR = i.Field<String>("CD_CR"), CD_APPLI = i.Field<String>("CD_APPLI"), CD_TRT = i.Field<String>("CD_TRT"), LB_TRT = i.Field<String>("LB_TRT"),
PERIODE = i.Field<Int64>("PERIODE"), CD_JOB = i.Field<String>("CD_JOB"), LB_JOB = i.Field<String>("LB_JOB"), CD_TYP_TRT = i.Field<String>("CD_TYP_TRT"),
CD_TRT_SSIS = i.Field<String>("CD_TRT_SSIS"), DT_DEB = i.Field<DateTime>("DT_DEB"), DT_FIN = i.Field<DateTime>("DT_FIN"), DUREE = i.Field<String>("DUREE"),
TIMING = i.Field<String>("TIMING")
}).ToList();
return View(query);
SubCR contains the value that the user select in the list box, SubCR is of type string[].
I've tried to do a where on my list CondCR but it returns nothing and I don't know if it comes from my query or from an other thing.
Have you some suggestions ?
Okay, I've find the answer, I just had to do this in my query :
where CondCR.Contains(i.Field<String>("CD_CR").Trim()) && CondAppli.Contains(i.Field<String>("CD_APPLI").Trim())

Get Child Content Types of a Content Type

How can I get the child content types of a content type?
From here I've learned that, all the child content types have the contentTypeId begins with the parent's ID. So, I tried to use the suggested way that is in the link.
Let me show you what I've tried first:
using (var site = new SPSite(SPContext.Current.Site.ID))
{
using (var web = site.RootWeb)
{
SPContentTypeId ctId = new SPContentTypeId(MasterContentTypeId);
SPContentType masterCt = web.ContentTypes[ctId];
var queryString = string.Empty;
queryString += "<Where>";
queryString += "<BeginsWith>";
queryString += "<FieldRef Name='ContentTypeId'/>";
queryString += "<Value Type='Text'>";
queryString += MasterContentTypeId;
queryString += "</Value>";
queryString += "</BeginsWith>";
queryString += "</Where>";
SPSiteDataQuery query = new SPSiteDataQuery { Query = queryString };
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
foreach (DataRow row in dt.Rows)
{
//Do Something Necessary
}
}
}
But the DataTable returns with no rows.
Is this the right way to do this but there's something missing or wrong; or am I doing this all wrong?
I guess I've found a solution.
Here is the reference: link
IEnumerable<SPContentType> descendantContentTypes = from SPContentType childCt in web.AvailableContentTypes
where childCt.Id.IsChildOf(parentContentTypeId)
select childCt;

Resources