Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm using
ElementAtOrDefault()
and I want to set my own default value

What I have tried:

Something like this:
string[] list_of_strings ={"ala", "ma","mala" }
set default="something"
string q =list_of_strings.ElementAtOrDefault(0)
string x =list_of_strings.ElementAtOrDefault(1)
string y =list_of_strings.ElementAtOrDefault(2)
string z =list_of_strings.ElementAtOrDefault(3)
Console.Write(q + Environment.NewLine);
Console.Write(x + Environment.NewLine);
Console.Write(y + Environment.NewLine);
Console.Write(z + Environment.NewLine);


Output:
ala
ma
mala
something

Is it possible?
Posted
Updated 15-Nov-20 23:51pm
Comments
F-ES Sitecore 28-Sep-20 12:45pm    
You'd have to write your own extension method as the one you're using doesn't support that.
aksimoN 28-Sep-20 15:43pm    
tnx

 
Share this answer
 
Comments
aksimoN 28-Sep-20 12:52pm    
There's nothing about setting default value
Richard MacCutchan 28-Sep-20 14:37pm    
The sample code shows how.
aksimoN 28-Sep-20 15:42pm    
The sample code shows only what happend when index is out of range. There is nothing about setting diffrent default value
Richard MacCutchan 29-Sep-20 3:24am    
Quote:The default value for reference and nullable types is null.
Richard MacCutchan 29-Sep-20 3:26am    
You can also implement IList<T>.Item[Int32] Property (System.Collections.Generic) | Microsoft Docs[^] in your own class and set a default value for the Item[] property.
Marc Gravell (StackOverFlow) published useful generic extension methods for this years ago: [^].
 
Share this answer
 
I was looking for something like this:
string abc = List_of_strings[4].name ?? "something";


It's working perfect for me because when you ask about a object that doesn't exist you will get "NONE" instead of error.
 
Share this answer
 
v2
Comments
Richard Deeming 16-Nov-20 6:20am    
If List_of_strings doesn't contain five elements, you will still get an error.

If List_of_strings[4] returns null, you will still get an error.
aksimoN 17-Nov-20 3:23am    
I'm using something like this:

cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = member?.state ?? "none";

and it's working for me, where member.state has no value.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900