如何在 linq 中调用没有返回类型的方法?

发布于 2024-10-08 22:45:42 字数 421 浏览 3 评论 0原文

我喜欢在 linq 中或在 linq 的扩展方法中调用没有返回类型的方法? 在这里,我的班级有情况线,

Class A
{
   int i;
   public int K
   {
     get { return i; }
     set { i = value; }
   }
   public void calculate(int z)
   {
     this.k=z;
   }
}

我喜欢这样做,

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

仅此示例,我喜欢这样做以达到我的目的。

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

一绘本一梦想 2024-10-15 22:45:42

您应该使用 List.ForEach这里。

sam.ForEach(s => s.calculate(somenumber));

我认为您在问题中使用 .Select 是因为您想获得结果(调用 calculate 后 A 的所有实例)。您可以通过变量sam直接获取它们。 ForEach 修改 sam 的每个元素,并将“更改”应用于列表本身。

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.

隐诗 2024-10-15 22:45:42

如果您的意思是要迭代序列 (IEnumerable) 并调用对于它的代码,您可以使用一个操作来实现扩展方法,该操作会为序列中的每个项目调用,例如:

public static void ForEach<T>(this System.Collection.Generic.IEnumerable<T> list, System.Action<T> action)
{
    foreach (T item in list)
        action(item);
}

如果您想调用小逻辑(一行)而不实现 foreach() 块,那么这是有意义的:

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 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());
}
心病无药医 2024-10-15 22:45:42

如果不需要结果,可以用随机值填充结果(例如false)。

var c = sam.Select( s => {s.calculate(4); return false;} );

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;} );
何以畏孤独 2024-10-15 22:45:42

经常使用这种方法:

通用方法:

from item in sequence

// wrapping statements with lambda
let @void = new Func<bool>(() => {
   // whatever you like..
   return true;
})()

select item

如果您想进行属性分配(额外奖励:示例如何使用 HTTP 客户端:-):

..
// 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

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
孤者何惧 2024-10-15 22:45:42

我最近遇到了这个问题。我有时发现我更喜欢 LINQ 的声明语法...

这是我的调用,

// wont compile:
from ticket in actualTickets
group ticket by ticket.ID into ticketGroup
select AddToBasket( exhibition, ticketGroup.First(), ticketGroup.Count() );

我想不出让 AddToBasket() 返回任何内容的好理由,所以我重构如下:

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

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();
千柳 2024-10-15 22:45:42

我最近有同样的需求,反应性地调用操作,并编写了一个 Do() 流处理函数,用于 1) 将操作包装到具有返回值的仿函数中,2) 在流上进行选择。

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

请注意,此实用程序函数仍然必须将流转换为 List() 才能逐字调用每个流项的操作。

var numbers = new List<int> { 1, 2, 3 };
var sum = 0;
numbers
    .Do(it => { sum += it; })
    .ToList();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文