2009-09-08 21 views
0

根据要求,我们必须以相反顺序或C# - 集合是足够的还是LINQ的组合将提高性能?

返回一个集合。我们,始平程序员设计的集合如下:(样品给出)

namespace Linqfying 

{ 

class linqy 

    { 
     static void Main() 

     { 

     InvestigationReport rpt=new InvestigationReport(); 

     // rpt.GetDocuments(true) refers 
     // to return the collection in reverse order  


      foreach( EnquiryDocument doc in rpt.GetDocuments(true) ) 
      { 

       // printing document title and author name  

      } 
     } 
    } 




class EnquiryDocument 

    { 
     string _docTitle; 

     string _docAuthor; 

     // properties to get and set doc title and author name goes below 


     public EnquiryDocument(string title,string author) 

     { 
     _docAuthor = author; 

     _docTitle = title; 
     } 

     public EnquiryDocument(){} 

} 



    class InvestigationReport 

    { 

     EnquiryDocument[] docs=new EnquiryDocument[3]; 

     public IEnumerable<EnquiryDocument> GetDocuments(bool IsReverseOrder) 

     { 

      /* some business logic to retrieve the document 

      docs[0]=new EnquiryDocument("FundAbuse","Margon"); 

      docs[1]=new EnquiryDocument("Sexual Harassment","Philliphe"); 

       docs[2]=new EnquiryDocument("Missing Resource","Goel"); 

     */ 


     //if reverse order is preferred 

      if(IsReverseOrder) 
      { 

       for (int i = docs.Length; i != 0; i--) 
       yield return docs[i-1]; 

      } 

     else 
      { 
      foreach (EnquiryDocument doc in docs) 
     { 
      yield return doc; 
      } 
     } 

     } 

} 

} 

问:

  • 我们可以使用其他集合类型,以提高工作效率?
  • Collection with LINQ的混合减少代码? (我们对LINQ不熟悉)

回答

1

对我来说看起来不错。是的,你可以使用Reverse扩展方法......但这不会像你所得到的那样高效。

虽然你关心效率多少?我会用最多的可读的解决方案(即Reverse),直到你知道效率是一个问题。除非收藏很大,否则不太可能成为问题。

如果您已将“原始数据”作为数组使用,那么使用迭代器块将比调用Reverse更有效。 Reverse方法将缓冲所有数据,然后每次产生一个项目 - 就像您自己的代码一样,真的。然而,简单地打电话Reverse会简单得多...

除了其他任何东西,我会说这是值得你学习LINQ - 至少LINQ到对象。它可以使处理数据更加清洁,比以前更加清洁。

+0

谢谢大家,我们会按照你的建议。 – user160677 2009-09-08 22:06:58

+0

我们的项目主管刚刚下了一个命令,“即使在他上学的时候,他也没有编写这么糟糕的代码”。我们感到震惊,这就是我们发布这个的原因。谢谢大家。 – user160677 2009-09-08 22:10:56

1

两个问题:

  1. 功能的代码,你现在有工作?
  2. 你是否认为这段代码是你的性能瓶颈?

如果其中任何一个问题的答案都是否定的,请不要担心。只是让它工作,继续前进。代码没有任何严重错误,所以不需要烦恼!花点时间去构建新的功能。保存LINQ以解决您尚未解决的新问题。

+0

是的,它运作良好。感谢雷克斯。 – user160677 2009-09-08 22:11:41

0

你GetDocuments方法的IEnumerable返回类型,所以没有必要甚至遍历您的数组时IsReverseOrder是假的,你可以回到它是数组类型的IEnumerable ...

至于当IsReverseOrder为true时,可以使用Array.Reverse或Linq Reverse()扩展方法来减少代码量。

+0

谢谢Simon:) – user160677 2009-09-08 22:28:01

相关问题