According to the requirement we have to return a collection either in reverse order or as
it is. We, beginning level programmer designed the collection as follow :(sample is given)
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;
}
}
}
}
}
Question :
- Can we use other collection type to improve efficiency ?
- Mixing of Collection with LINQ reduce the code ? (We are not familiar with LINQ)
Looks fine to me. Yes, you could use the
Reverseextension method… but that won’t be as efficient as what you’ve got.How much do you care about the efficiency though? I’d go with the most readable solution (namely
Reverse) until you know that efficiency is a problem. Unless the collection is large, it’s unlikely to be an issue.If you’ve got the “raw data” as an array, then your use of an iterator block will be more efficient than calling
Reverse. TheReversemethod will buffer up all the data before yielding it one item at a time – just like your own code does, really. However, simply callingReversewould be a lot simpler…Aside from anything else, I’d say it’s well worth you learning LINQ – at least LINQ to Objects. It can make processing data much, much cleaner than before.