开发者

how call method without return-type in linq?

i like to call a method without return-type in linq or in extension methods in linq? Here my class i have situation line this

Class A
{
   int i;
   public int K
   {
     get { return i; }
     set { i = value; }
   }
   public void calculate(int z)
   {
     this.k=z;
开发者_如何学C   }
}

i like to do like this

List<A> sam = new List<A>();
//add elements to this list
var c = sam.Select( s => s.calculate(4) );

this sample only , i like to do like this for my purpose.


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.


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());
}


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;} );


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();


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


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜