<(E-Mail Removed)> wrote:
> I am looking to reduce my code size because I have many very simliar
> functions e.g.:
>
> private uint GenerateAcquisitionID(AcquisitionType[] c)
> {
> uint max = 0;
> foreach (AcquisitionType a in c)
> {
> uint n = Convert.ToUInt32(a.acquisitionID);
> if (n > max) max = n;
> }
> return max + 1;
> }
>
> private uint GenerateContentID(ContentType[] c)
> {
> uint max = 0;
> foreach (ContentType a in c)
> {
> uint n = Convert.ToUInt32(a.contentID);
> if (n > max) max = n;
> }
> return max + 1;
> }
What you could do is use an anonymous delegate for the conversion,
keeping the rest of the logic in one place. Here's a short but complete
example:
using System;
class Test
{
static void Main()
{
string[] strings = {"Hello", "Jon", "123456"};
Console.WriteLine (MaxPlusOne
(strings, delegate (string x) { return (uint)x.Length; } ));
}
private static uint MaxPlusOne<T> (T[] items,
Converter<T,uint> converter)
{
uint max = 0;
foreach (T item in items)
{
uint n = converter(item);
if (n > max) max = n;
}
return max + 1;
}
}
--
Jon Skeet - <(E-Mail Removed)>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too