集合中运行的所有对象的方法 [英] Run a method on all objects within a collection

查看:98
本文介绍了集合中运行的所有对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有Bloops的集合创建金酸梅的集合。我检索使用LINQ查询此集合。参考:<一href="http://stackoverflow.com/questions/923238/linq-select-certain-properties-into-another-object">http://stackoverflow.com/questions/923238/linq-select-certain-properties-into-another-object为查询

So I have a collection of Razzies created from a Collection of Bloops. I retrieve this collection using a Linq query. Reference:http://stackoverflow.com/questions/923238/linq-select-certain-properties-into-another-object for the query.

我想知道是否有可能返回集合之前运行的所有新创建的金酸梅的方法,或甚至右后,只是不使用for循环。

I would like to know if it is possible to run a method on all of the newly created Razzies before returning the collection, or even right after, just without using a for-loop.

我尝试这样做:

Dim results = From item In bloops _
              Select New Razzie() With _
              { _
                  .FirstName = item.FirstName, _
                  .LastName = item.LastName _
              }.UpdateAddress(item.Address)

但它没有返回值。

But it returns nothing.

推荐答案

拉斯,这可能会做你想做的。这是一个pretty的简单的方法。如果这不是你想要的,请展开你的问题。

Russ, this might do what you want. It's a pretty simple approach. If this is not what you want, please expand your question.

这将每个元素为您列举了它们运行的​​方法。它将不可以运行方法,直到你枚举,但你可以放心地知道,该方法的您使用的数据之前运行。

This will run the method on each element as you enumerate over them. It will not run the method until you enumerate, but you can safely know that the method will run before you use the data.

修改由于您使用的是密封的第三方类,使用扩展方法。这就是他们的东西。 ;)修改code使用扩展方法

EDIT Since you are using a sealed 3rd party class, use extension methods. That's what they're for. ;) Modified code to use extension methods.

class MyArgs { }
class Razzie //pretend this is a 3rd party class that we can't edit
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
static class RazzieExtensions
{
    public static Razzie MyMethod(this Razzie razzie, MyArgs args)
    {
        razzie.FirstName = razzie.FirstName.ToUpper();
        return razzie;
    }
}
class Program
{
    static void Main(string[] args)
    {
        var bloops = new List<Razzie>
            {
                new Razzie{FirstName = "name"},
                new Razzie{FirstName = "nAmE"}
            };
        var myArgs = new MyArgs();
        var results = from item in bloops
                      select new Razzie
                      {
                          FirstName = item.FirstName,
                          LastName = item.LastName
                      }.MyMethod(myArgs);

        foreach (var r in results)
            Console.WriteLine(r.FirstName);
        Console.ReadKey();
    }
}

这篇关于集合中运行的所有对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆