2012-05-02 41 views
2

我有以下的功能,但它是非常长的,肮脏的,我想优化它:的foreach得到下一个项目

 //some code 
     if (use_option1 == true) 
     { 
      foreach (ListViewItem item in listView1) 
      { 
       //1. get subitems into a List<string> 
       // 
       //2. process the result using many lines of code 
      } 
     } 
     else if (use_option2 = true) 
     { 
      //1. get a string from another List<string> 
      // 
      //2. process the result using many lines of code 
     } 
     else 
     { 
      //1. get a string from another List<string> (2) 
      // 
      //2. process the result using many lines of code 
     } 

这是工作非常好,但它是非常肮脏 我想用这样的:

 //some code 
     if (use_option1 == true) 
     { 
      List<string> result = get_item();//get subitems into a List<string> 
     } 
     else if (use_option2 = true) 
     { 
      //get a string from another List<string> 
     } 
     else 
     { 
      //get a string from another List<string> (2) 
     } 


      //process the result using many lines of code 


     private void get_item() 
     { 
      //foreach bla bla 
     } 

我该如何让get_item函数每次获取列表中的下一个项目?

我读了一些关于GetEnumerator的内容,但我不知道如果这是解决我的问题或如何使用它。

+1

每个选项的处理代码是否相似? – Justin

+1

在第一个代码段中,这个“// 2。使用多行代码处理结果”的评论,这是同一个过程吗? –

+0

是的,它是一样的,但我不能在一个函数内部使用它,因为从开始的代码(/ /某些代码)。所以唯一的选择是从void使用foreach – ShaMora

回答

0

您可以在官方文档阅读本 - 举例:MSDN reference

+1

这只是一个链接,还是你的意思是“LINQ”? – sinelaw

+0

我已经读过关于IEnumerable.GetEnumerator方法,但我是一个C#初学者,所以我不知道如何实现它 – ShaMora

+0

没有人知道? – ShaMora

1

看一看的yield keyword它是有效的,并返回一个IEnumerable。请看下面的例子:

 List<string> list = new List<string> { "A112", "A222", "B3243" }; 

     foreach(string s in GetItems(list)) 
     { 
      Debug.WriteLine(s); 
     } 

如果你有一个GetItems方法定义如下:

public System.Collections.IEnumerable GetItems(List<string> lst) 
{ 
    foreach (string s in lst) 
    { 
     //Some condition here to filter the list 
     if (s.StartsWith("A")) 
     { 
      yield return s; 
     } 
    } 
} 

你的情况,你会是这样的:

public System.Collections.IEnumerable GetItems() 
{ 
    for (ListViewItem in ListView) 
    { 
     //Get string from ListViewItem and specify a filtering condition 
     string str = //Get string from ListViewItem 
     //Filter condition . e.g. if(str = x) 
     yield return str; 
    } 
} 

如果你想要去进一步使用LINQ,那么它会下降到一行:

public System.Collections.IEnumerable GetItems(List<string> lst) 
{ 
    return lst.Where(T => T.StartsWith("A")); 
} 

希望这是有用的。