score:6
If you mean that you want to iterate a sequence (IEnumerable) and invoke code for it, you can inplement an extension method with an action, that is invoked for each item in the sequence, e.g.:
public static void ForEach<T>(this System.Collection.Generic.IEnumerable<T> list, System.Action<T> action)
{
foreach (T item in list)
action(item);
}
This makes sense if you want to invoke small logic (one line) without implementing a foreach() block:
public class MyClass
{
public void DoSomethingInOneLine()
{
// do something
}
}
public static void Test(System.Collections.Generic.IEnumerable<MyClass> list)
{
list.ForEach(item => item.DoSomethingInOneLine());
}
score:0
I recently ran into this issue. I sometimes find I prefer the declerative syntax of LINQ...
this was my call
// wont compile:
from ticket in actualTickets
group ticket by ticket.ID into ticketGroup
select AddToBasket( exhibition, ticketGroup.First(), ticketGroup.Count() );
I couldn't think of a good reason to make AddToBasket()
return anything, so I refactored as follows:
var pendingOpperations = from ticket in actualTickets
group ticket by ticket.ID into ticketGroup
select new Action( () => AddToBasket( exhibition, ticketGroup.First(), ticketGroup.Count() ) );
foreach ( var action in pendingOpperations ) action.Invoke();
score:0
Using this often:
Generic approach:
from item in sequence
// wrapping statements with lambda
let @void = new Func<bool>(() => {
// whatever you like..
return true;
})()
select item
If you want to do property assignment (bonus: example how to work with HTTP client :-):
..
// inside fluent LINQ query
let client = new HttpClient()
// initialise property and discard result
let @discard = client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("user:pass")))
// now work with initialised client according to your logic..
select client.GetAsync("url").Result.Content.ReadAsStringAsync().Result
score:0
I had the same requirement recently, call the action reactively and I write a Do() stream processing function for 1) wrapping the action into a functor with a return value and 2) selecting on the stream.
public static IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source,
Action<TSource> action) {
TSource doSelector(TSource src) {
action.Invoke(src);
return src;
}
return source
.Select(it => doSelector(it));
}
Please note that this utility function still has to convert the stream into List() to literally call the action for each stream item.
var numbers = new List<int> { 1, 2, 3 };
var sum = 0;
numbers
.Do(it => { sum += it; })
.ToList();
score:5
If you don't need the result, you can fill the result with a random value (e.g. false
).
var c = sam.Select( s => {s.calculate(4); return false;} );
score:10
You should use List<T>.ForEach
here.
sam.ForEach(s => s.calculate(somenumber));
I think you use .Select
in your question because you want to get the results(all the instances of A after calling calculate
). You can get them directly by the variable sam
. ForEach
modifies each elements of sam, and the "changes" are applied to the list itself.
Source: stackoverflow.com
Related Query
- How to return anonymous type from c# method that uses LINQ to SQL
- How to get linq `ForEach` statement to return data on the method call being made for each list object?
- LINQ Is it possible to get a method name without a return type via LINQ expression trees?
- How to call a function from Linq statement without a return value?
- How to call a method within .Select in Linq query without having to write select twice?
- Return partial linq query from method - how to declare return type
- How can I filter a dictionary using LINQ and return it to a dictionary from the same type
- How can I call local method in Linq to Entities query?
- How to understand the following C# linq code of implementing the algorithm to return all combinations of k elements from n
- how call method without return-type in linq?
- Linq Query syntax vs. Method Chain: return type
- LINQ and how to return a list of a specific type
- How to call a method in the where clause of a LINQ query on a IQueryable object
- How to call custom method in linq query
- LINQ to SQL(.dbml): how do ExecuteQuery method return DataTable?
- Moq: how to call method predicate inside linq to mocks query?
- How to return list of items from linq to sql query and call it in a console application
- How to make a return type for a result set in LINQ
- How can I call a method from within a LINQ expression?
- How to await (in async method) a linq request containg a c# method call
- LINQ Group By Sum how do i return null for decimal type field
- How can I set custom property of an Entity type in LINQ to Entities query and still return a IQueryable<T>?
- How to Select top (5) contributors group by Business type code in c# linq query
- How to return query results from method that uses LINQ to SQL
- How to return Anonymous Type while using Linq
- How to specify .NET Anonymous object return type in Linq using Func<T,Q>?
- how to call .Where() method in linq more than once to act like OR (||)
- Why did I get an exception "Cannot implicitly convert type 'bool' to 'long?'" when using the LINQ Sum method and how to fix it?
- How do I finnangle the type that linq outputs into the function's return type
- How to cast my Linq query to the expected Web API return type
More Query from same tag
- How to get the index of each item that is null in a List<T> via Linq
- EF4.2 extra left outer join to same table
- LInq Order By and Order By Desc
- Operator '??' cannot be applied to operands of type 'System.Guid?' and 'string'
- How to select with multiple condition in linq?
- Entity framework and local cache of database tables
- specifying the foreign key to the table programmatically by using fluentapi
- I have a custom expression program with a lexer, parser and evaluator. How do I LINQ-ify it?
- ASP.Net C# MVC Group domain model and place results into ViewModel
- LINQ - list group by
- Calculating hourly breakdown of minutes in each hour for a period of time
- Self Join or Inner Query in a table with Linq to SQL
- Linq Join issue in C#
- Linq: Xml to IEnumerable<KeyValuePair<int, string>> deferred execution?
- LINQ to XML: filter a query using XElement.Attributes() collection with both XName and Value
- Lambda Expression on boolean
- System.InvalidCastException: Specified cast is not valid (linq query)
- Collapse repeated columns into sublist
- LINQ multiple order by
- How to update multiple items in list
- How to convert List<string> to Dictionary<string,string> using linq?
- LINQ - Join only one attribute with whole schema onf another entity
- EF6 Query Criteria using object properties that aren't null
- Conversion of a LINQ query fom method syntax to query syntax
- Index out of range error
- Good way to connect parent table/entity with child table/entities?
- How to extend a class from Model.tt
- How to make the following join?
- Find max and min date from different property
- How to create a strongly type view when I have join in query which I am using in Action method?