Hi how can I ignore null values in a reader c# in my statement =>
LegalDesc = reader["legal1"].ToString() + ' ' +
reader["legal2"].ToString() + ' ' +
reader["legal3"].ToString();
Scenario: if legal2 is a null value the resulting string would be
legalDesc = legal1 + ' ' + legal3
How could apply iif used in VB?
You could use a collection and String.Join:
List<string> legals = new List<string>();
if(!reader.IsDbNull(reader.GetOrdinal("legal1")))
legals.Add(reader["legal1"].ToString());
if(!reader.IsDbNull(reader.GetOrdinal("legal2")))
legals.Add(reader["legal2"].ToString());
if(!reader.IsDbNull(reader.GetOrdinal("legal3")))
legals.Add(reader["legal3"].ToString());
LegalDesc = string.Join(" ", legals);
Of course you could also make the code more elegant by using a custom extension method:
public static string SafeGetString(this SqlDataReader reader, int colIndex)
{
if(!reader.IsDBNull(colIndex))
return reader.GetString(colIndex);
else
return string.Empty;
}
Now you can use:
string[] legals = { reader.SafeGetString(0), reader.SafeGetString(1), reader.SafeGetString(2) };
LegalDesc = string.Join(" ", legals.Where(s => !string.IsNullOrEmpty(s)));
This presumes that it's actually a string column and the column ordinal positions are from 0 to 2. If that's not the case use above shown reader.GetOrdinal approach to detect them.
Using a simple extension method:
public static string ValueOrEmpty(this object source)
{
return source == null ? string.Empty : source.ToString();
}
var values = new[] { reader["legal1"],reader["legal2"],reader["legal3"] };
LegalDesc = string.Join(" ",
values.Select(x => x.ValueOrEmpty())
.Where(x => x != string.Empty));
First
Do Not do string concatenation like that, every time you concatenate, it creates a new instance of string because string is Immutable. There is a C# class that handles appends and it's StringBuilder
So try implementing it like this
StringBuilder builder = new StringBuilder();
builder.Append(reader["legal1"])
.Append(" ")
.Append(reader["legal2"])
.Append(" ")
.Append(reader["legal3"]);
Console.WriteLine(builder.ToString());
Console.ReadKey();
This way, you don't even need to check if it's null.
Hi I just to want rephrase my problem...
how can view a value to a LegalDesc = reader["legal1"].ToString() if legal1 is null?
I am viewing my result in a grid and so the grid shows NULL in the cell. The result should be a blank space instead of NULL....
in VB net I could use the IIf function if null then blank space...
Related
While creating service to display OpenFileDialog/SaveFileDialog, I was thinking about creating LINQ query/clear C# code to Concatinate()/Join() filter expression.
Do the filter based on this call:
string res = "";
if(new Service().ShowOpenFileDialog(out res,
new string[]{ "JPG", "TXT", "FBX"},
new string[]{ "Images", "TextFile", "FilmBox"}))
Console.WriteLine(res); //DisplayResult
Example definition:
public bool ShowOpenFileDialog(out string result, string[] ext, string[] desc)
{
if(ext.Length != desc.Length) return false;
OpenFileDialog diag = new OpenFileDialog();
// problematic part
// diag.Filter = "Text File (*.txt)|*.txt";
// diag.Filter = desc[0] + " (*." + ext[0] + ")|*." + ext[0];
// diag.Filter += "|"+desc[1] + " (*." + ext[1] + ")|*." + ext[1];
// I tried something like:
// diag.Filter = String.Join("|", desc.Concat(" (*." + ext[0] + ")|*." + ext[0]));
// but not sure how to pass indexes across LINQ queries
diag.Filter = /* LINQ? */
if(diag.ShowDialog() == true)
{
result = diag.FileName;
return true;
}
return false;
}
Question: Is it possible to create LINQ to concatenate/join 2 arrays in such format? Is it needed to do it by code? If so, what is the cleanest/least expensive solution?
Note: As a filter (result) example:
"Images (*.JPG)|*.JPG |TextFile (*.TXT)|*.TXT |FilmBox (*.FBX)|*.FBX"
EDIT: Also please consider there might be n items in the arrays.
You should use Select to iterate over your collection. Also, string interpolation comes in handy here.
string filter = string.Join
( "|"
, ext.Zip
( desc
, (e, d) => new
{ Ext = e
, Desc = d
}
)
.Select(item => $"{item.Desc} (*.{item.Ext})|*.{item.Ext}")
);
I am trying to create dynamic syntax function and function syntax is like below:
MyFunction( arg1,arg2,ar3.....);
I have string like this:
str = Previousvalue.Value1,Previousvalue.Value2
Now I would like to create syntax like this in final variable :
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2);
str = Previousvalue.Value1,Previousvalue.Value2,Previousvalue.Value3;
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
This is how I am trying to achieve with string.join (without using loop) but not getting how to do it and this seems like impossible to do without using loop:
final = string.Join("MyFunction(", str.Split(','));
Case 1:
Input : string str =Previousvalue.Value1,Previousvalue.Value2
Output:
string final=MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
Case 2 :
Input : str = Previousvalue.Value1,Previousvalue.Value2,Previousvalue.Value3;
output:
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
Case 3:
string input = " Previousvalue.Value1";
Output:
String final = Previousvalue.Value1; //No function
From what I understand, you want to generate a string like this:
"MyFunction(Previousvalue.Value1,',',Previousvalue.Value2);"
^..........^...................^....^...................^.
prefix arg1 sep arg2 suffix
or in other words
prefix = "MyFunction(";
separator = ",',',";
suffix = ");"
which can be achieved by moving the prefix and suffix out of the string.Join and using the above separator value:
string final = "MyFunction(" + string.Join(",',',", str.Split(',')) + ");";
Also instead of Split / Join you could simply use string.Replace:
string final = "MyFunction(" + str.Replace(",", ",',',") + ");";
From my understanding of the problem you want to call the MyFunction method with n string parameters, but also with string[]. You can do it like this:
public static void Main(string[] args)
{
string str = "Test1,Test2,Test3";
string test1 = MyFunction("Test1", "Test2", "Test3");
string test2 = MyFunction(str.Split(','));
}
public static string MyFunction(params string[] parameters)
{
StringBuilder sb = new StringBuilder();
foreach(var item in parameters)
{
sb.AppendLine(item);
}
return sb.ToString();
}
Try :
public string MyJoin(params string[] vars)
{
return "MyFunction(" + string.Join(",", vars) + ");";
}
I need to split this data in the box to and add it to new line when it see the ";"
var retryParamInfo = new ExParamsContent
{
Idenitifier = tempIdentifier.SerialNumber,
Name = String.Format( "Retry Information Console {0}",i),
Value = MyTestRunGlobals.FixtureComponents[i].Uuts[0].RetryList,
//Value = thisUut.RetryList.Replace("\n", "\n" + Environment.NewLine),
};
uutTempInfo.ExParams.Add(retryParamInfo);
To split a string when some character occours, you can use:
myString.split(';');
and make the result of this be inside a array.
All I have is a file and a string to be searched inside it
Key
Value1
Value2
Value3
Key1
Value1
This is the structure of the file. Now, I search for a key and then read all values under it
until I find a newline (or simply a empty line)
I use this algorithm.
var valuelist = new List<string>();
using(var reader = new StreamReader(#"c:\test.txt"))
{
String a;
while( (a=reader.ReadLine())!=null)
{
if(!a.Equals("Key")) continue;
while( a == reader.ReadLine() != null) //check whether end of file is not reached.
{
if(a.Length == 0) break; //a empty line is reached.hence comeout.
valuelist.add(a);
}
}
}
I am using "using" because it automatically disposes the "reader" object ? Is my approach right in this case ?
How Can I use a LINQ expression here in this context ?
I tried the following code
var all_lines = File.ReadAllLines(#"C:\test.txt");
//How to retrieve "Values" for a given key using LINQ ?
The use of using in this context is very appropriate
To retrieve the values for a given key, you can use SkipWhile looking for the key by name, followed by TakeWhile looking for a blank line.
var list = new List<string>{
"junk", " a", " b", "", "key", " c", " d", " e", "", "more", "f"
};
var vals = list.SkipWhile(s => s != "key").Skip(1).TakeWhile(s => s != "");
foreach (var s in vals) {
Console.WriteLine(s);
}
Here is the source code for this test:
var tags = new List<string> {"Portland", "Code","StackExcahnge" };
const string separator = " ";
tagString = tags.Aggregate(t => , separator);
Console.WriteLine(tagString);
// Expecting to see "Portland Code StackExchange"
Console.ReadKey();
Update
Here is the solution I am now using:
var tagString = string.Join(separator, tags.ToArray());
Turns out string.Join does what I need.
For that you can just use string.Join.
string result = tags.Aggregate((acc, s) => acc + separator + s);
or simply
string result = string.Join(separator, tags);
String.Join Method may be?
This is what I use
public static string Join(this IEnumerable<string> strings, string seperator)
{
return string.Join(seperator, strings.ToArray());
}
And then it looks like this
tagString = tags.Join(" ")