How to check if string is null in c#.net [duplicate] - c#

This question already has answers here:
How to check if String is null
(6 answers)
Most performant way of checking empty strings in C# [closed]
(8 answers)
Closed 6 years ago.
I am reading text file in c#.net
at the end one line is completely null but in foreach c# can not detect null string so It gets error
string[] lines = System.IO.File.ReadAllLines(dir);
List<KeyValuePair<int, DateTime>> items = new List<KeyValuePair<int, DateTime>>();
List<KeyValuePair<int, DateTime>> lst = new List<KeyValuePair<int, DateTime>>();
foreach (string line in lines)
{
if (line!=string.Empty)
{
l = line.Split('\t');
l[0] = l[0].Trim();
PersianCalendar persCal = new PersianCalendar();
SqlConnection sqlconn = new SqlConnection(DBsetting.Connstring);
SqlCommand sqlda = new SqlCommand("InsertReadd", sqlconn);
sqlda.CommandType = CommandType.StoredProcedure;
sqlda.Parameters.AddWithValue("#date", l[1]);
sqlda.Parameters.AddWithValue("#IDp", l[0]);
sqlda.Parameters.AddWithValue("#day", GetDayOfWeek(GetPerDate(l[1])));
sqlda.Parameters.AddWithValue("#nobatkari", "");
sqlda.Connection.Open();
sqlda.ExecuteNonQuery();
sqlda.Connection.Close();
}
}
RefGrid();

if(!String.IsNullOrEmpty(line))
just do this and it works
It checks for Null and Empty. This is the used everywhere for this functionality in C#.
EDIT:
You can use the following for checking strings which contains whitespaces.
if(!String.IsNullOrWhiteSpace(line))

CHECK
change:
if (line!=string.Empty)
to:
//check if the sting = null or empty
if (!String.IsNullOrEmpty(line))
{
//some code
}

Related

How to find duplicate keys from a List<KeyValuePair<byte[], string>> fileHashList = new List<KeyValuePair<byte[], string>>(); [duplicate]

This question already has answers here:
Group by array contents
(1 answer)
Easiest way to compare arrays in C#
(19 answers)
Closed 2 years ago.
I've a lsit of type List<KeyValuePair<byte[], string>> fileHashList = new List<KeyValuePair<byte[], string>>();
foreach (string entry in results)
{
FileInfo fileInfo = new FileInfo(Path.Combine("DirectoryPath"), entry));
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(fileInfo.FullName))
{
var hash = md5.ComputeHash(stream);
fileHashList.Add(new KeyValuePair<byte[], string>(hash, fileInfo.FullName));
}
}
}
I need to find all the duplicate keys in this list.
I tried this but doesn't work in my case, I get "Enumeration yielded no results" even though I've same keys!
Let me know if any additional data is needed
Thanks

Use Variable for Control Name [duplicate]

This question already has answers here:
C#: how to get an object by the name stored in String?
(4 answers)
Get value of a variable using its name in a string
(2 answers)
Getting variable by name in C#
(1 answer)
Closed 3 years ago.
I have created multiple List and want to use each individual List when I have a variable name.
For example:
private List<string> listAlabama = new List<string>();
private List<string> listTexas = new List<string>();
// fill Lists with values
//Call Method to assign state to correct list
AssignNameToList("Alabama");
private void AssignNameToList(string state)
{
// Assign variable to the correct List e.g
sring tempFindList="list"+state;
//Use the right List
string tempVal=tempFindList[0]???
// should be listAlabama
}
Below is the solution I came up with using a Dictionary
var dictionary = new Dictionary<string, List<string>>();
dictionary.Add("Alabama", listAlabama);
dictionary.Add("Texas", listTexas);
switch (tempState)
{
case "Alabama":
List<string> value = dictionary["Alabama"];
Console.WriteLine(value);
string[] tempArray = value[totalPopulationIdx].Split(',');

How to create an interpolated string from a string? [duplicate]

This question already has answers here:
C#6.0 string interpolation localization
(9 answers)
Closed 3 years ago.
I'm working on a system that gets templates from a database, then fills in values programmatically:
//using System.Runtime.CompilerServices;
var template = "Hello {0}"; // this string comes from the database
var name = "Joe";
var message = FormattableStringFactory.Create(template, new object[] { name });
Console.WriteLine(message);
This code sample works, but I can only use the numeric notation. I'd like to store the templates in the database in the interpolated string format, like this:
var template = "Hello {name}";
This throws a Run-time exception (line __): Input string was not in a correct format.
Is it possible to create an interpolated string from a string?
I do something similar in a (probably) weird way.... but it works so i try to share with you my conclusion:
public static string ExtendedStringFormat(this string source, List<Tuple<string, string>> values)
{
string returnvalue = source;
foreach(Tuple<string, string> my_touple in values)
{
returnvalue = returnvalue.Replace(string.Concat('{', my_touple.Item1, '}'), my_touple.Item2);
}
return returnvalue;
}
And you can call it like below:
List<Tuple<string, string>> lst = new List<Tuple<string,string>>();
lst.Add(new Tuple<string, string>("test","YAYYYYYY"));
lst.Add(new Tuple<string, string>("test2","YAYYYYYY22222222"));
string ret = "hem... hi? {test}, {test2}";
ret = ret.ExtendedStringFormat(lst);

Adding elements to List<> doesn't work [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a List<> declared, which is accessable in the whole class
List<article> data;
Now I'm using a method to fill the List<>:
StreamReader sr = new StreamReader(filePath);
while (!sr.EndOfStream)
{
string[] Line = sr.ReadLine().Split(';');
article newArticle = new article();
newArticle.articleNumber = Line[0];
newArticle.description = Line[1];
newArticle.articleId = Line[2];
try
{
data.Add(newArticle);
}
catch(NullReferenceException ex)
{
// Nothing to do here
}
}
Each time, the loop repeats, the newArticle-Object contains all his elements, so it is definetely not null.
But it doesn't add to the data-List<>.
What am I missing?
In order to add items to the list, you must first initialise it.
Replace:
List<article> data;
with:
List<article> data = new List<article>();

c# - regex to find a string that comes after = [duplicate]

This question already has answers here:
regex to find a string that comes after =
(6 answers)
Closed 9 years ago.
So I asked this question before and said I wanted it in javascript but realized later on that it's unecessary data being sent. So it would be great if anybody could help me solve the same thing in C#
What I need is to get several properties out of a string.
The string will look something like:
str = "car[brand=saab][wheels=4]";
There can be more or fewer properties.
I need everything before the first [] in 1 variable.
Then I need each property and its value in a variable.
Easiest way to understand what I want is probably to check my previous question and the answer that solved it :)
I used the regex(slightly different) in your previous question.
string input = "car[brand=saab][wheels=4]";
string product = "";
Dictionary<string, string> props = new Dictionary<string, string>();
foreach (Match m in Regex.Matches(input, #"^(\w+)|\[(\w+)=(.+?)\]"))
{
if (String.IsNullOrEmpty(product))
product = m.Groups[1].Value;
else
props.Add(m.Groups[2].Value, m.Groups[3].Value);
}
try this regex:
(.+?)(\[.+?\])+
and a sample code:
var inputString = "car[brand=saab][wheels=4]";
var pattern = #"(?<v1>.+?)(?<v2>\[.+?\])+";
var v1 = Regex.Match(inputString, pattern).Groups["v1"].Value;
Dictionary<String, String> list = new Dictionary<String, String>();
foreach (Capture capture in Regex.Match(inputString, pattern).Groups["v2"].Captures)
{
var sp = capture.Value.Split('=');
list.Add(sp[0], sp[1]);
}
explain:
(?<name>subexpression)
Captures the matched subexpression into a named group.
You can do this
var lst=Regex.Matches(input,#"(\w+)((?:\[.*?\])+)")
.Cast<Match>()
.Select(x=>new
{
name=x.Groups[1].Value,
value=Regex.Matches(x.Groups[2].Value,#"(?<=\[).*?(?=\])")
.Cast<Match>()
.Select(x=>new
{
name=x.Groups[0].Value.Split('=')[0],
value=x.Groups[0].Value.Split('=')[1]
})
});
Now you can iterate over lst like this
foreach(var parent in lst)
{
parent.name;//car
foreach(var pairs in parent.value)
{
pairs.name;//brand,wheels
pairs.value;//ferrari,4
}
}
So,for input car[brand=a][wheels=4]cycle[brand=b][wheels=2]
Output would be like
car
brand,a
wheels,4
cycle
brand,b
wheels,2
Without regex:
string input = "car[brand=saab][wheels=4]";
var query = from s in input.Replace("]", "").Split('[')
let vars = s.Split('=')
let name = vars[0]
let value = vars.Length > 1 ? vars[1] : ""
select new {Name = name, Value = value};
string firstVar = query.First().Name;
Dictionary<string, string> otherVars = query
.Skip(1)
.ToDictionary(v => v.Name, v => v.Value);
You can access your variables in the dictionary like this string brand = otherVars["brand"]
Since you already have an answer using regex and your comments state it doesn't have to be with a regex, I'll offer an alternative:
The code is
string str = ("car[brand=saab][wheels=4]");
int i = str.IndexOf("[");
string[] details =str.Substring(i).Replace("]","").Split('[');
string name = str.Substring(0, i);
string brand = details[1].Split('=')[1];
string wheels = details[2].Split('=')[1];
This approach assumes the data is always going to be in the same format though; you may need some validation in there depending on your needs...

Categories