The use of custom enumerators is an elegant way to filter a list.
Sometimes a function has to be called on different filtered sets with some changes to the parameters.
This sniplet will offer you an elegant way of doing so.
It can for instance be used to write different tags in an XML file (implement the non-provided DoWriteTag method; or any other)
private void DoWrite(IEnumerable enm, string tagName) is the actual example, the other code was added to illustrate its use.
// both Capability and OperationMode are held in the List<Group> this.capabilities
// useEnumerate.DoWrite shows how th build a generic call to handle subsets of this.capabilities.
// It offers an elegant and very readable call because the Enumerator is a parameter of the method
using System.Collections;
using System.Collections.Generic;
namespace Sniplet
{
#region Help Classes
// example base class
public class Group
{
public bool Included
{
get
{
return true;
}
}
}
// example Capability
public class Capability : Group
{
public Capability()
:base()
{
}
}
// Example OperationMode
public class OperationMode : Group
{
public OperationMode()
: base()
{
}
}
#endregion;
public class useEnumerate
{
private List<Group> capabilities;
public useEnumerate()
{
this.capabilities = new List<Group>();
// todo: fill this.capabilities
}
/// <summary>
/// since the enumerator is a part of the method this call automatically filters on this.capabilities
/// It enables you to handle each subset differently, for instance by providing a different tagName
/// </summary>
/// <param name="enm">The filter that will provide you with a subset of this.capabilities </param>
/// <param name="tagName">example of an additional parameter for the call</param>
/// <returns></returns>
private void DoWrite(IEnumerable enm, string tagName)
{
foreach (Group g in enm)
{
// Do something on the chosen subset of capabilities
// e.g.
// DoWriteTag(tagname);
}
}
/// <summary>
/// Example of a call to DoWrite
/// </summary>
/// <returns></returns>
protected void WriteTagNames()
{
DoWrite(this.ContainedCapabilities, "capability");
DoWrite(this.ContainedOperationModes, "mode");
}
#region Iterators
// enumerate Capabilities
internal IEnumerable<Capability> ContainedCapabilities
{
get
{
for (int i = 0; i < this.capabilities.Count; i++)
{
if ((this.capabilities[i] is Capability) && (this.capabilities[i].Included == true))
{
yield return this.capabilities[i] as Capability;
}
}
}
}
// enumerate modes
internal IEnumerable<OperationMode> ContainedOperationModes
{
get
{
for (int i = 0; i < this.capabilities.Count; i++)
{
if ((this.capabilities[i] is OperationMode) && (this.capabilities[i].Included == true))
{
yield return this.capabilities[i] as OperationMode;
}
}
}
}
#endregion;
}
}
Kommentare zum Snippet