English 中文(简体)
通过列表和执行功能循环
原标题:Looping through list and executing function
  • 时间:2012-05-23 15:26:55
  •  标签:
  • c#

我有一个包含多个其他对象列表的物体模型。 我要循环浏览列表中的每个对象, 并对它们执行一种方法。 方法叫做 MyMethod, 列表中的每个对象在分类定义中都有这个方法 。

这就是我所拥有的:

public class MyObject
{
  public List<NestedObject1> ListNestedObject1 { get; set; }
  public List<NestedObject2> ListNestedObject2 { get; set; }

  public void ExecuteMethodsOfNestedObjectLists()
  {
    if (ListNestedObject1.Count > 0) { from a in ListNestedObject1 a.MyMethod();}
    if (ListNestedObject2.Count > 0) { from a in ListNestedObject2 a.MyMethod();}
  }
}

我试图测试每个嵌套对象列表的长度, 并对每个元素执行 MyMethod 。 我知道我可以做一个前置循环, 但我想看看如何使用 linq 语法来保持其简短 。

我该怎么改写它才能成功?

谢谢

最佳回答

所以,你问 如何执行这个方法 对于每一个嵌套的物体?

ListNestedObject1.ForEach(obj => obj.MyMethod());
ListNestedObject2.ForEach(obj => obj.MyMethod()); 

注:List.ForEach 不是LINQ(尽管其外观相似),在.NET 2. 0中引入。

问题回答

你应该用前环,这是它的目的

Linq 设计用于查询数据, 且不设计用于造成副作用。 您所要寻找的是一种 Linq < code> ForEach 扩展方法。 Eric Lippert < a href=" http://blogs. msdn.com/b/ ericlippert/ archive/2009/05/18/ foreach- vs- forache.aspx" rel= “ nofol” >explain 为什么这在语言中故意省略了 < / em > 。 如果您感兴趣, 请更详细地说一下 。

当然,你可自由地无视这些哲学问题,自行撰写自己的ForEach 方法。

取代

 if (ListNestedObject1.Count > 0) { from a in ListNestedObject1 a.MyMethod(); }

使用使用

    if (ListNestedObject1.Count > 0)
    { 
        ListNestedObject1.Select(
        a=>
            { 
                a.MyMethod(); 
                return a;
            } 
    }

类似地替换 listNestedObject2 的查询

您可以使用 < a href=> http://msdn. microsoft.com/ en- us/library/bwabdf9z.aspx" rel = "nofollow" > ForEach 扩展方法 List<T> , 这与 foreach /code > 环完全相同。 请注意, > Ienubolable<T> 环上无法使用这个方法, 一般来说, 是否应该使用这个方法, 而不是 foreach 环, 是激烈辩论的。

MyObject.ListNestedObject1.ForEach(MyMethod);
MyObject.ListNestedObject2.ForEach(MyMethod);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签