I have the following....
var jobsApplications = ( from applications in db.applications
where applications.employeeId == LogedUser.Id
select new { applications.id, applications.jobId, applications.confirmationDate });
Now I want to navigate this result like
foreach "something" in jobsApplications
But I don't now what to put in something since the select new create a new class.
Any suggestions
I guess you can let the compiler do the work for you:
foreach (var application in jobApplications)
{
// use the application wisely
}
Consider using Array.ForEach() to iterate through your IEnumerable or List. This is a bit more heavyweight.
Array.ForEach(jobsApplication, jobApp => {
if (jobApp.City == "Chicago")
{
jobApp.Approved = true;
}
});
If you want a simple foreach, then you can type the anonymous class as var
foreach (var jobApp in jobApplications)
{
if (jobApp.City == "Chicago")
{
jobApp.Approved = true;
}
}
Related
Description
My goal is to compare the language of a menu object from the menuList. Since the menuList has the Languages offered as another list it makes it a bit more complicated. So I tried to create a new class object with the same values so I can use menuList.Languages.Contains(languageObject), however I quickly found out that this doesn't work like that. I tried to make a for loop inside a for loop which didn't work either, but could be a failure from my side.
Obviously I can't write something like: MenuList.Languages.Name.Equals("English").
Because of that I am looking for a solution where I can check if the attribute Name of the Languages-List inside the menuList equals a value of my choice.
The Object
private LanguageBox LangEng = new LanguageBox
{
IsoCode = "eng",
Name = "English"
};
The List
var MenuList = menuDataClient.GetMenuByCity(city)
.Select(nap => new MenuBox()
{
Menu = nap.Menu,
Languages = nap.Languages
.Select(lang => new LanguageBox()
{
IsoCode = lang.IsoCode,
Name = lang.Name
}).ToList()
})
.ToList();
The Loop
for (int i = 0; i < MenuList.Count; i++)
{
if (MenuList[i].Languages.Contains(LangEng))
{
System.Console.WriteLine("Success");
}
}
Maybe linq's Where could do the trick? Sth like:
foreach(var item in MenuList)
{
var x = item.Languages.Where(obj => obj.Name == <desired language>);
if (x.Count() > 0)
{
//Success code
break;
}
}
I have found a solution. This LINQ option works if you want to only keep elements in the list which have English or Russian in their Languages-List.
Solution
.Where(lang => lang.Languages.Any(any => any.Name.Equals("English") || any.Name.Equals("Russian")))
I managed to make a selection from the complex structure of the object, but only with the help of foreach, how can I avoid this foreach and solve my problem, just using LINQ?
var product = new List<ProductCrp>
{
new ProductCrp {
Strucutre = new StructureItem() {
CheckList = new CheckList() {
Checks = new List<Check>
{
new Check { NumberAsInt = "149" },
new Check { NumberAsInt = "260" },
new Check { NumberAsInt = null }
}
}
}
},
new ProductCrp {
Strucutre = new StructureItem() {
CheckList = new CheckList() {
Checks = new List<Check>
{
new Check { NumberAsInt = "261" },
new Check { NumberAsInt = "150" },
new Check { NumberAsInt = "260" }
}
}
}
}
};
string[] numbers = { "149" };
LINQ:
foreach (var item in product)
{
item.Strucutre.CheckList.Checks = item.Strucutre.CheckList.Checks.Where(w => numbers.Contains(w.NumberAsInt)).Select(w => w);
}
I managed to make a selection from the complex structure of the object, but only with the help of foreach, how can I avoid this foreach and solve my problem, just using LINQ?
You do not use LINQ for this purpose. You are using foreach correctly.
LINQ is for querying data. A foreach loop is about producing a side effect repeatedly. The body of your foreach is mutating a property of an object; that's an update and not a query, so you are doing it right. Using LINQ for that is wrong; don't do it.
Answers that say to, for instance, use ToList to force iteration of a query with a side effect are extremely bad style and result in code which is inefficient, hard to understand, hard to maintain, and works against the purpose of the query operators. NEVER abuse LINQ like that. We have a construct built into the language that means "perform this operation once per collection element", and it is called foreach. Use it.
Are you looking for something like this?
product.ForEach(item => item.Strucutre.CheckList.Checks = item.Strucutre.CheckList.Checks.Where(w => numbers.Contains(w.NumberAsInt)).Select(w => w).ToList());
I need to access items from a list which is i am accessing with the following code
foreach (var reportval in reportresponse)
{
foreach (var valitem in reportval.Comparison)
{
var responsemodel = new ReportResponseModel();
responsemodel.StudentVariable = valitem.StudentVariable;
responsemodel.Lighter = valitem.Lighter;
responsemodel.Matched = valitem.Matched;
responsemodel.Stronger = valitem.Stronger;
reportResponseModel.Add(responsemodel);
}
};
I tried the following code to exit the loop without retiterting the first loop. But its not working.
if (reportresponse.Count == reportResponseModel.Count) { break; };
also i tried the following way to access the inner list from the first loop but its not accessible here
foreach (var reportval in reportresponse.Comparison)
Can someone please help on this?
Did you try like this
foreach (var reportval in reportresponse.Comparison)
{
// var responsemodel = new ReportResponseModel();
responsemodel.StudentVariable = valitem.StudentVariable;
responsemodel.Lighter = reportval .Lighter;
responsemodel.Matched = reportval .Matched;
responsemodel.Stronger = reportval .Stronger;
//reportResponseModel.Add(responsemodel);
}
};
Have you tried Linq's SelectMany?
You can do something like
var reportResponseModel = reportresponse.SelectMany(r => r.Comparison, (r, c) =>
new ReportResponseModel
{
StudentVariable = c.StudentVariable,
Lighter = c.Lighter,
Matched = c.Matched,
Stronger = c.Stronger
});
Then you can apply additional filtering like with .Where or .Take to have only needed count of items.
I updated the code with the following changes.
if (reportresponse.Count == reportResponseModel.Count)
{ return reportResponseModel; };
after
reportResponseModel.Add(responsemodel);
Thanks #Stephen Muecke !!
In the code below, .Contains() only return string that start with the text I type in the TextBox. I want it to return all records that contain that string anywhere in the the searched field. Please advise how I can get Contains() to return the value, alternate ways are welcome as well
Thanks
using (var GC = new GroundCommanderEntities())
{
foreach (var Current in GC.IMF_Extensions.Where(filter => filter.Description.Contains(Search_txt.Text) ))
{
string sss = Current.Description;
Coll.Add(sss);
}
// tried same result foreach (var Current in GC.IMF_Extensions.Where(filter => filter.Description.Contains(Search_txt.Text.Trim()) || filter.Description.StartsWith(Search_txt.Text) || filter.Description.EndsWith(Search_txt.Text)))
// tried same result foreach (var Current in GC.IMF_Extensions.Where(filter => filter.Description.Contains(Search_txt.Text.Trim()) ))
}
Try a simpler method without Linq:
using (var GC = new GroundCommanderEntities())
{
foreach (var Current in GC.IMF_Extensions)
{
if (Current.Description.Contains(Search_txt.Text))
{
Coll.Add(Current.Description);
}
}
}
Try to use ToLower for both strings before Contains. It should be work.
using (var GC = new GroundCommanderEntities())
{
foreach (var Current in GC.IMF_Extensions.Where(filter => filter.Description.ToLower().Contains(Search_txt.Text.ToLower())))
{
Coll.Add(Current.Description);
}
}
I'm just trying to teach myself how to use Linq. This is what I have
if (FileReceivers.Exists(t => t.FileName == filename))
{
//I also want to do a c.Parent = proper FileReceiver
FileReceivers.Where(t=>t.FileName == filename).First().Clients.Add(c);
}
else
{
FileReceiver fr = new FileReceiver(filename);
fr.Clients.Add(c);
FileReceivers.Add(fr);
}
Any ideas how I would do this the right way? I don't really want to be using Linq to twice to grab the same thing, that would defeat the purpose.
I would just like to know the proper way to format this.
var fr = FileReceivers.FirstOrDefault(t=>t.FileName == filename);
if (fr == null) {
fr = new FileReceiver(filename);
FileReceivers.Add(fr);
}
fr.Clients.Add(c);
you could always pass the results of t => t.FileName == filename to an anonymous type and use that for later processing.