C#: Convert List to List
If I have objects that implement or inherits from a parent, I can cast them implicitly to their base class:
Here KorrespondanseParameter implements IPurrefrister:
KorrespondanseParameter k=new KorrespondanseParameter();
IPurrefrister deadline= k;
or even:
IPurrefrister deadline= new KorrespondanseParameter();
Same with this where NytegningAktoerRetur inherits from NytegningRetur:
NytegningAktoerRetur nar=new NytegningAktoerRetur();
NytegningRetur obj= nar;
Often I have some kind of List of objects that I want to cast to it something else.
One could think that this should work:
List< KorrespondanseParameter> list=new List< KorrespondanseParameter>();
List< IPurrefrister> plist=list;
or explicit:
List< IPurrefrister> plist= (List< IPurrefrister>) list;
neither compiles.
Solution with delegates:
List<KorrespondanseParamer> to List<IPurrefrister> where
public static List<IPurrefrister> LagIPurrefrister(List<KorrespondanseParameter> korr)
{
if (korr != null)
{
return korr.ConvertAll<IPurrefrister>(
delegate(KorrespondanseParameter k)
{
return k;
});
}
else
{
return null;
}
}
lambda:
IEnumerable<NytegningAktoerRetur> to List<NytegningRetur>
List<NytegningRetur> liste = TilbudsListe.ToList().ConvertAll<NytegningRetur>(t=> t);
Nice and short :)
rgds
Henri
C# Handy extension methods to check if a value/object is set or not
if(!string.IsNullOrEmpty(param.ID))
….something
earlier I made an extension method for this:
public static bool IsNullOrEmpty(this string test)
{
return String.IsNullOrEmpty(test);
}
which gives you nicer code like this
if(!param.ID.IsNullOrEmpty())
…. something
I usually make this as well:
public static bool IsNotNullOrEmpty(this string test)
{
return !String.IsNullOrEmpty(test);
}
giving:
if(param.ID.IsNotNullOrEmpty())
…. something
But today I was checking parameters on a webservice and started to want these methods for all my parameteres, so here goes:
public static bool IsNull(this object @object)
{
return @object == null;
}
public static bool IsNullOrDefault<T>(this T value)
{
return value.IsNull() ? true : trueEqualityComparer<T>.Default.Equals(value, default(T)) ;
}
this returns true if
object == null
int == 0
bool == false
etc.
Then I didn't quite like the way it looked in code:
if(!param.ID.IsNullOrDefault())
…. something
so I made a couple of aliases:
public static bool ErSatt<T>(this T value)
{
return value.IsNotNullOrDefault();
}
public static bool ErIkkeSatt<T>(this T value)
{
return value.IsNullOrDefault();
}
that's nice in norwegian, in english they could be named something like:
public static bool IsSet<T>(this T value)
public static bool IsNotSet<T>(this T value)
Anyhow I can now write the first line:
if(!string.IsNullOrEmpty(param.ID))
….something
like this
if(param.ID.ErSatt())
….something
or in english:
if(param.ID.IsSet())
….something
much more intuitive in my book ;)
rgds
HM
1 comment :
Post a Comment