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())
Related
I have a controller that accepts a list of strings. THese strings essentially are IDs that a user selects on the view. I need to build the model based upon fields from to tables, hence the need for the join. The bellow code will not build as it claims the properties from the joined table do not exist. It only accepts table 1 values. Item.Well_No and Item.Well_Name throw the error. These are included in the "y" table that i joined to "x"..
[HttpPost]
public ActionResult buildSelectionTable(List<string> dta)
{
var a = from x in db._AGREEMENTS
join y in db.WELL_AGMT_XREF on x.AGMT_NUM equals y.AGMT_NUM
where dta.Contains(x.AGMT_NUM)
select x;
List<AgmtModel> model = new List<AgmtModel>();
foreach (var item in a)
{
model.Add(new AgmtModel { Agmt_Name = item.AGMT_NAME, Agmt_Num = item.AGMT_NUM, Agmt_Type = item.AGMT_TYPE_DESCR, Amnt_Status = item.AGMT_STAT_DESCR, Company = item.CO_NAME, DaysToExp = item.DaysToExp, Drs_Url = item.DRS_URL, Effective_Date = item.EFF_DT, Orig_Lessee = item.ORIG_LESSEE, Prop_Status = item.AGMT_PROP_STAT_DESCR, Expiration_Date = item.EXPR_DATE, Acreage = item.LGL_AREA, Extention_Expiration = item.EXTN_EXPR_DT, WellNo = item.WELL_NO, Well_Name = item.WELL_NAME });
}
return PartialView("_SelectionTable", model);
}
You are only selecting x in your query you need to also select y and reference it.
change select x to be select new { x, y}
and then
foreach (var item in a)
{
model.Add(new AgmtModel { Agmt_Name = item.y.AGMT_NAME, Agmt_Num = item.x.AGMT_NUM ... });
}
you need to insert .x or .y before you the field to determine the field names
alternatively you could actually put the constructor directly in the query
so instead of select x
select new AgmtModel { Agmt_Name = y.AGMT_NAME, etc...}
then you can just return PartialView("_SelectionTable", a.ToList())
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
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
var getAllProducts = _productService.GetAllProducts();
if (productstest.Count > 0)
{
model.idproduct.Add(new SelectListItem()
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
foreach (var m in getAllProducts)
model.idproduct.Add(new SelectListItem()
{
Value = m.Id.ToString(),
**Text = m.Size.Distinct().ToString(),**
Selected = model.Pid == m.Id
});
}
public virtual IList<Product> GetAllProducts(bool showHidden = false)
{
var query = from p in _productRepository.Table
orderby p.Name
where (showHidden || p.Published) &&
!p.Deleted
select p;
var products = query.ToList();
return products;
}
The issue is even i tried to populate the select list with distinct size using: Text = m.Size.Distinct().ToString(), but it shows the duplicate for instance 100 products are of size 33 cm , the list will populate the dropdownlist in the view with 33cm occuring 100 times , I dont want to show 100 times , just want to show 1 time, Can any one assist me with this issue ?
Presumably you are only trying to show one product of each different size... if so initialising your getAllProducts variable like so will do the trick:
var getAllProducts = _productService.GetAllProducts().GroupBy(p => p.Size).Select(g => g.First());
I have the following code which adapts linq entities to my Domain objects:
return from g in DBContext.Gigs
select new DO.Gig
{
ID = g.ID,
Name = g.Name,
Description = g.Description,
StartDate = g.Date,
EndDate = g.EndDate,
IsDeleted = g.IsDeleted,
Created = g.Created,
TicketPrice = g.TicketPrice
};
This works very nicely.
However I now want to populate a domain object Venue object and add it to the gig in the same statement. Heres my attempt....
return from g in DBContext.Gigs
join venue in DBContext.Venues on g.VenueID equals venue.ID
select new DO.Gig
{
ID = g.ID,
Name = g.Name,
Description = g.Description,
StartDate = g.Date,
EndDate = g.EndDate,
IsDeleted = g.IsDeleted,
Created = g.Created,
TicketPrice = g.TicketPrice,
Venue = from v in DBContext.Venues
where v.ID == g.VenueID
select new DO.Venue
{
ID = v.ID,
Name = v.Name,
Address = v.Address,
Telephone = v.Telephone,
URL = v.Website
}
};
However this doesnt compile!!!
Is it possible to adapt children objects using the "select new" approach?
What am I doing so very very wrong?
Your inner LINQ query returns several objects, not just one. You want to wrap it with a call like:
Venue = (from v in DBContext.Venues
where v.ID == g.VenueID
select new DO.Venue
{
ID = v.ID,
Name = v.Name,
Address = v.Address,
Telephone = v.Telephone,
URL = v.Website
}).SingleOrDefault()
Your choice of Single() vs. SingleOrDefault() vs. First() vs. FirstOrDefault() depends on what kind of query it is, but I'm guessing you want one of the first two. (The "OrDefault" variants return null if the query has no data; the others throw.)
I also agree with Mike that a join might be more in line with what you wanted, if there's a singular relationship involved.
Why are you doing a join and a sub select? You can just use the results of your join in the creation of a new Venue. Be aware that if there is not a one to one relationship between gigs and venues you could run into trouble.
Try this:
return from g in DBContext.Gigs
join venue in DBContext.Venues on g.VenueID equals venue.ID
select new DO.Gig { ID = g.ID, Name = g.Name, Description = g.Description,
StartDate = g.Date, EndDate = g.EndDate, IsDeleted = g.IsDeleted,
Created = g.Created, TicketPrice = g.TicketPrice,
Venue = new DO.Venue { ID = venue.ID, Name = venue.Name,
Address = venue.Address, Telephone = v.Telephone,
URL = v.Website }