I have the following code which would开发者_运维百科 return me a value if it is present in the array "arrayID".
string str = arrayID.Single(s => s == ((System.Data.DataRowView)(e.Item.DataItem)).Row["ID"].ToString());
The problem I'm facing now is that when the value is not present I get the error
Sequence contains no matching element
I would like to have an empty string returned incase the value is not present in arrayID.
Kindly let me know how this can be done in linq.
Thanks in advance.
The SingleOrDefault
method is what you're after. If no item exists, it will return the default value (null), so you'll just need another step to convert that to empty:
string str = arrayID
.SingleOrDefault(s => s == ((System.Data.DataRowView)(e.Item.DataItem)).Row["ID"].ToString())
?? string.Empty
Default in SingleOrDefault refers to the C# default keyword. So when nothing is found the default of the source value is returned.
http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx
So just be aware that the default of a value type will not be null.
For example:
int[] list = { 1, 3, 7, 13,21};
int v;
try {
v=list.Single(n => n > 15);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
int? v2;
v2 = list.SingleOrDefault(n => n > 30);
Console.WriteLine(v2.ToString());
// output: 0
int v3;
v3=list.SingleOrDefault(n => n > 30);
Console.WriteLine(v3.ToString());
// output: 0
string[] slist = {"a", "b", "c"};
var v4 = slist.SingleOrDefault(s => s == "z");
Console.WriteLine(v4==null);
// output: true <-- i.e. it is a reference type + it is nullable.
精彩评论