Linq throwing exception when Null is returned to a string - attribute on a class?
I have a Linq query which I am selecting into a string, of course a string can contain null!
So is there a way I can throw an exception within my Linq query, if I detect a null?
Can I decorate my class with an attribute that won't let it allow null?
I would like to wrap my Linq query in a try catch, and as soon as a null is detected then it would enter the catch, and I can handle it.
Edit
Here's my Linq query, it's quite simple currently. I am going开发者_JAVA技巧 to extend it, but this shows the basic shape:
var localText = from t in items select new Items { item = t.name }
Basically item is set to t.name, t.name is a string so it could be empty / null is this perfectly legal as its a string and strings can hold NULL.
So if it returns NULL then I need to throw an exception. Actually it would be handy to be able to throw an exception is NULL or empty.
I seemed to remember some kind of Attributes that can be set on top of properties that says "Don't accept null" etc.?
Edit
I think I found it: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx
This doesn't allow null or strings so I presume it throws an exception, I have used this with MVC but I am not sure if I can use it with a standard class.
As a string being null isn't particularly exceptional, you could do something like:
var items = myStrings.Where(s => !string.IsNullOrEmpty(s)).Select(s => new Item(s));
UPDATE
If you are reading this data from an XML file, then you should look into LINQ to XML, and also use XSD to validate the XML file rather than throwing exceptions on elements or attributes that don't contain strings.
You could try intentionally generating a NullReferenceException:
try
{
//Doesn't change the output, but throws if that string is null.
myStrings.Select(s=>s.ToString());
}
catch(NullReferenceException ex)
{
...
}
You could also create an extension method you could tack on to a String that would throw if null:
public static void ThrowIfNull(this string s, Exception ex)
{
if(s == null) throw ex;
}
...
myString.ThrowIfNull(new NullReferenceException());
Why do you want to throw an exception in this case? This sounds like throwing the baby out with the bath water for something that should not happen in the first place.
If you just want to detect that there are null/empty items:
int nullCount= items.Count( x=> string.IsNullOrEmpty(x.name));
If you want to filter them out:
var localText = from t in items where !string.IsNullOrEmpty(t.name) select new Items { item = t.name };
精彩评论