如何在linq中使用return-type的call方法?

时间:2010-12-27 06:45:49

标签: c# linq methods

我想在linq或linq的扩展方法中调用一个没有return-type的方法? 在这里我的班级我有情况这一行

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

这个样本,我喜欢这样做。

6 个答案:

答案 0 :(得分:8)

您应该在这里使用List<T>.ForEach

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

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

答案 1 :(得分:6)

如果您想要迭代序列(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());
}

答案 2 :(得分:4)

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

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

答案 3 :(得分:0)

我最近遇到过这个问题。我有时会发现我更喜欢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();

答案 4 :(得分:0)

经常使用这个:

通用方法:

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

答案 5 :(得分:0)

最近我有相同的要求,以反应方式调用该动作,我编写了一个Do()流处理函数,用于1)将动作包装到具有返回值的函子中,以及2)在流上进行选择。

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",

    "configurations": [
        {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": false
        },
        {
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "port": 5678,
            "host": "localhost",
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "."
                }
            ]
        },
        {
            "name": "Python: Module",
            "type": "python",
            "request": "launch",
            "module": "enter-your-module-name-here",
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "console": "integratedTerminal",
            "args": [
                "runserver",
                "--noreload",
                "--nothreading"
            ],
            "django": true
        },
        {
            "name": "Python: Flask",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "app.py"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true
        },
        {
            "name": "Python: Current File (External Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "externalTerminal"
        },
        {
            "name": "Debug Unit Test",
            "type": "python",
            "request": "attach",
            "justMyCode": false
        }
    ]
}

请注意,此实用程序函数仍必须将流转换为List(),以从字面上调用每个流项目的操作。

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