how to invoke a method for each item using LINQ? - c#

I am trying to get a method invoked for each item in a list while passing that method the list item itself. Basically I can do it the drawn out way but was trying to get it in a concise LINQ statement like so:
var urls = html.DocumentNode.SelectNodes("//a[#href]")
.Select(a => a.Attributes["href"].Value)
.Where(href => !href.StartsWith("mailto:")) // skip emails, find only url links
.ToList();
//.ToList().ForEach(href => getWEbData(href.ToString ()));
foreach (string s in urls) {
getWEbData(s);
}
I could not figure out how to get the .ForEach() in to the LINQ
shorthand or if its possible.

You can't. LINQ functions are designed to not cause side effects. ForEach is designed to cause side effects. Hence, there is no ForEach LINQ function.
See "foreach" vs "ForEach" by Eric Lippert

Don't try to use foreach with Linq. Id adds no values and makes it harder to debug. You can embed the query in the foreach call like so:
foreach (string s in html.DocumentNode
.SelectNodes("//a[#href]")
.Select(a => a.Attributes["href"].Value)
.Where(href => !href.StartsWith("mailto:")))
{
getWEbData(s);
}
Note that ToList() is unnecessary (whether you do the query inside or outside of the foreach)

you can use foreach with Linq but its better to have a constructor i.e. in Select statement take a new class object and make a parameterized constructor of that class an in the constructor you can do whatever you want it is one of the easiest and efficient way.

There is no LINQ .ForEach method, but you can easily write your own:
public static class IEnumerableExtensions {
public static void ForEach<T>(this IEnumerable<T> pEnumerable, Action<T> pAction) {
foreach (var item in pEnumerable)
pAction(item);
}
}
and then
html
.DocumentNode
.SelectNodes("//a[#href]")
.Select(a => a.Attributes["href"].Value)
.Where(href => !href.StartsWith("mailto:")) // skip emails, find only url links
.ForEach(href => getWEbData(href.ToString ()));
or slightly better (although I think href may already be a string):
...
.Select(href => href.ToString())
.ForEach(getWEbData);
Although, as others have indicated, just because you can doesn't necessarily mean you should, but that was not your question.

Related

Can I connect a AsObservable easy to an Observer

I have a LinQ Expression resulting in a IEnumerable<string> statements.
This I want to route to an Observer with a ForEach() via OnNext.
Now I see a hint about using Reactive Extensions instead of ForEach and the code looks like this.
statements.ToObservable().Subscribe(
s => this.statementObserver.OnNext(new Statement(replyTo, jobId, s)));
// foreach (var s in statements)
// {
// this.statementObserver.OnNext(new Statement(replyTo, jobId, s));
// }
Is this correct or can I directly connect my statements to the statementObserver ?
You can do either of the methods you've suggested, but this might be the more idiomatic way to do it:
statements
.ToObservable()
.Select(s => new Statement(replyTo, jobId, s))
.Subscribe(this.statementObserver);
Do be careful exposing observers like that though. One call to .OnCompleted() and you've killed your object. It's best to pass in the observable and let the class observe it how it likes.

Select multiple types in LINQ Select

Can this be turned into a select statement?
foreach (var gf in CreateGenericFieldsOnInspection(model))
{
simpleInspection.GenericFields.Add(gf.GenericFieldDefinition.Name,
new LC360Carrier.Domain.Models.Import.GenericField
{
GenericFieldType = GenericFieldValueType.Text,
Value = gf.Value
});
}
It looks like GenericFields is a Dictionary<string, GenericFieldOrSomething>. You could contort this into something really weird for the sake of using LINQ. But the purpose of LINQ is to query one or more IEnumerables to either get a result or transform them into something else.
It's just like SQL. You query it to either get a set of records or some value like the sum of some numbers.
In your case you've already got a result set - whatever CreateGenericFieldsOnInspection(model) returns. It makes sense to do what you're already doing - foreach through the results and perform some action on each one of them.
LINQ would be handy if you needed to query that set. For example,
var filteredProperties = CreateGenericFieldsOnInspection(model)
.Where(property => property.Name.StartsWith("X"));
But even then, once you had that collection, it would still make sense to use a foreach loop.
You'll see this sometimes - I did it when I first learned LINQ:
CreateGenericFieldsOnInspection(model).ToList()
.ForEach(property => DoSomethingWith(property));
We convert something to a List because then we can use .ForEach. But there's no benefit to it. It's just foreach with different syntax and an extra step.
I have an extension method that permits add. I was just having trouble w the syntax. Bagus Tesa, above was also helpful. Thanks.
simpleInspection.GenericFields = simpleInspection.GenericFields.Union(CreateGenericFieldsOnInspection(model).Select(x => new KeyValuePair<string, object>(x.GenericFieldDefinition.Name, new LC360Carrier.Domain.Models.Import.GenericField
{
GenericFieldType = GenericFieldValueType.Text,
Value = x.Value
}))).ToDictionary(x => x.Key, x => x.Value);

Nested foreaches into a chained linq expression [duplicate]

This question already has answers here:
LINQ expression instead of nested foreach loops
(7 answers)
Closed 9 years ago.
I don't know if it is even possible to do what I think, but I guess it worths to try :)
Can I combine these two nested foreaches?
foreach ( var dept in curDevice.Personnel.Department.Company.Departments )
{
foreach ( var personnel in dept.Personnels )
{
myPersonnels.Add(personnel);
}
}
I want to turn this nested for each into a chained linq expression. Is is possible? If so how?
Use Enumerable.SelectMany
foreach ( var personnel in
curDevice.Personnel.Department.Company.Departments.SelectMany(x=> x.Personnels))
{
myPersonnels.Add(personnel);
}
Use the SelectMany<TSource, TResult> method:
var allPersonnel = curDevice.Personnel.Department.Company.Departments.SelectMany(dept => dept.Personnels);
// If there is no AddRange method:
foreach (var personnel in allPersonnel)
myPersonnels.Add(personnel);
// If there is an AddRange method:
myPersonnels.AddRange(personnel)
This is personnel preference (see what I did there?), but I like sticking with functional programming if that's what I start with.
You can replace the foreach language construct with the List<T>.ForEach method.
curDevice.Personnel.Department.Company.Departments
.SelectMany(department => department.Personnels)
.ToList()
.ForEach(personnel => myPersonnels.Add(personnel);
Typically, we'd use a shorter argument name for the delegates:
curDevice.Personnel.Department.Company.Departments
.SelectMany(d => d.Personnels)
.ToList()
.ForEach(p => myPersonnels.Add(p);
And, if myPersonnels is just a collection, you can create it outright:
var myPersonnels = curDevice.Personnel.Department.Company.Departments
.SelectMany(d => d.Personnels)
.ToList();
Or, if it's already a List<T>, you can add an IEnumerable<T> to it:
myPersonnels.AddRange(
curDevice.Personnel.Department.Company.Departments
.SelectMany(d => d.Personnels)
);
Ken is almost right, but if I'm right the myPersonnels list is an external one where you want to copy the result of your "query". The first two answers are very readable, but if you want to code it shortly, you can write this:
curDevice.Personnel.Department.Company.Departments
.SelectMany(x => x.Personnels) // selecting the personnels
.ToList()
.Foreach(myPersonnels.Add); // iterate trough the personnels list and copy them into the external list

Replacing nested foreach with LINQ; modify and update a property deep within

Consider the requirement to change a data member on one or more properties of an object that is 5 or 6 levels deep.
There are sub-collections that need to be iterated through to get to the property that needs inspection & modification.
Here we're calling a method that cleans the street address of a Employee. Since we're changing data within the loops, the current implementation needs a for loop to prevent the exception:
Cannot assign to "someVariable" because it is a 'foreach iteration variable'
Here's the current algorithm (obfuscated) with nested foreach and a for.
foreach (var emp in company.internalData.Emps)
{
foreach (var addr in emp.privateData.Addresses)
{
int numberAddresses = addr.Items.Length;
for (int i = 0; i < numberAddresses; i++)
{
//transform this street address via a static method
if (addr.Items[i].Type =="StreetAddress")
addr.Items[i].Text = CleanStreetAddressLine(addr.Items[i].Text);
}
}
}
Question:
Can this algorithm be reimplemented using LINQ? The requirement is for the original collection to have its data changed by that static method call.
Update: I was thinking/leaning in the direction of a jQuery/selector type solution. I didn't specifically word this question in that way. I realize that I was over-reaching on that idea (no side-effects). Thanks to everyone! If there is such a way to perform a jQuery-like selector, please let's see it!
foreach(var item in company.internalData.Emps
.SelectMany(emp => emp.privateData.Addresses)
.SelectMany(addr => addr.Items)
.Where(addr => addr.Type == "StreetAddress"))
item.Text = CleanStreetAddressLine(item.Text);
var dirtyAddresses = company.internalData.Emps.SelectMany( x => x.privateData.Addresses )
.SelectMany(y => y.Items)
.Where( z => z.Type == "StreetAddress");
foreach(var addr in dirtyAddresses)
addr.Text = CleanStreetAddressLine(addr.Text);
LINQ is not intended to modify sets of objects. You wouldn't expect a SELECT sql statement to modify the values of the rows being selected, would you? It helps to remember what LINQ stands for - Language INtegrated Query. Modifying objects within a linq query is, IMHO, an anti-pattern.
Stan R.'s answer would be a better solution using a foreach loop, I think.
I don't like mixing "query comprehension" syntax and dotted-method-call syntax in the same statement.
I do like the idea of separating the query from the action. These are semantically distinct, so separating them in code often makes sense.
var addrItemQuery = from emp in company.internalData.Emps
from addr in emp.privateData.Addresses
from addrItem in addr.Items
where addrItem.Type == "StreetAddress"
select addrItem;
foreach (var addrItem in addrItemQuery)
{
addrItem.Text = CleanStreetAddressLine(addrItem.Text);
}
A few style notes about your code; these are personal, so I you may not agree:
In general, I avoid abbreviations (Emps, emp, addr)
Inconsistent names are more confusing (addr vs. Addresses): pick one and stick with it
The word "number" is ambigious. It can either be an identity ("Prisoner number 378 please step forward.") or a count ("the number of sheep in that field is 12."). Since we use both concepts in code a lot, it is valuable to get this clear. I use often use "index" for the first one and "count" for the second.
Having the type field be a string is a code smell. If you can make it an enum your code will probably be better off.
Dirty one-liner.
company.internalData.Emps.SelectMany(x => x.privateData.Addresses)
.SelectMany(x => x.Items)
.Where(x => x.Type == "StreetAddress")
.Select(x => { x.Text = CleanStreetAddressLine(x.Text); return x; });
LINQ does not provide the option of having side effects. however you could do:
company.internalData.Emps.SelectMany(emp => emp.Addresses).SelectMany(addr => Addr.Items).ToList().ForEach(/*either make an anonymous method or refactor your side effect code out to a method on its own*/);
You can do this, but you don't really want to. Several bloggers have talked about the functional nature of Linq, and if you look at all the MS supplied Linq methods, you will find that they don't produce side effects. They produce return values, but they don't change anything else. Search for the arguments over a Linq ForEach method, and you'll get a good explanation of this concept.
With that in mind, what you probaly want is something like this:
var addressItems = company.internalData.Emps.SelectMany(
emp => emp.privateData.Addresses.SelectMany(
addr => addr.Items
)
);
foreach (var item in addressItems)
{
...
}
However, if you do want to do exactly what you asked, then this is the direction you'll need to go:
var addressItems = company.internalData.Emps.SelectMany(
emp => emp.privateData.Addresses.SelectMany(
addr => addr.Items.Select(item =>
{
// Do the stuff
return item;
})
)
);
To update the LINQ result using FOREACH loop, I first create local ‘list’ variable and then perform the update using FOREACH Loop. The value are updated this way. Read more here:
How to update value of LINQ results using FOREACH loop
I cloned list and worked NET 4.7.2
List<TrendWords> ListCopy = new List<TrendWords>(sorted);
foreach (var words in stopWords)
{
foreach (var item in ListCopy.Where(w => w.word == words))
{
item.disabled = true;
}
}

Extension Method to assign value to a field in every item?

I could have sworn that there was an extension method already built for the Queryable class that I just can't find, but maybe I'm thinking of something different.
I'm looking for something along the lines of:
IQueryable<Entity> en = from e in IDB.Entities select e;
en.ForEach(foo => foo.Status = "Complete");
en.Foreach() would essential perform:
foreach(Entity foo in en){
foo.Status = "Complete";
}
Is this already written? If not, is it possible to write said Extension Method, preferably allowing for any LINQ Table and any Field on that table. Where is a good place to start?
There's nothing in the base class library. Many, many developers have this in their own common library, however, and we have it in MoreLINQ too.
It sort of goes against the spirit of LINQ, in that it's all about side-effects - but it's really useful, so I think pragmatism trumps dogma here.
One thing to note - there's really no point in using a query expression in your example. (It's not entirely redundant, but if you're not exposing the value it doesn't matter.) The select isn't doing anything useful here. You can just do:
IDB.Entities.ForEach(foo => foo.status = "Complete");
Even if you want to do a single "where" or "select" I'd normally use dot notation:
IDB.Entities.Where(foo => foo.Name == "fred")
.ForEach(foo => foo.status = "Complete");
Only use query expressions where they actually make the code simpler :)
public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
foreach (var item in sequence)
{
action(item);
}
}
There is a foreach on a List<>. Roughly something along these lines:
IQueryable<Entity> en = from e in IDB.Entities select e;
en.ToList().ForEach(foo => foo.status = "Complete");

Categories