Often I find myself filling ASP.NET repeaters with items that need the CSS class set depending on index: ‘first’ for index 0, ‘last’ for index (length-1), and ‘mid’ in the middle:
_repeater.DataSource = from f in foos select new { ..., CssClass = MakeCssClass( foos, f ) }; private static string MakeCssClass( Foo[] foos, Foo f ) { var index = Array.IndexOf( foos, f ); if( index == 0 ) { return 'first'; } else if( index == foos.Length - 1 ) { return 'last'; } else { return 'mid'; } }
Is there a nicer way I can achieve this (eg using lambda functions)? If I try I get CS0828, ‘Cannot assign lambda expression to anonymous type property’.
You might be interested in my SmartEnumerable type in MiscUtil.
From the usage page, there’s an example:
With implicitly typed variables and a bit more type inference the syntax could be tidied up quite easily. I must get round to that some time, but the basics are already there.