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>();
Related
This question already has answers here:
Split a List into smaller lists of N size [duplicate]
(21 answers)
Closed 3 years ago.
I'm using Csv Helper to write out a Linq Query with million of rows. I would like to split the output by, for instance, 1 million of rows each. Could I do that or should I use other type of writting method?
Here is my code:
var _path = UniversalVariables.outputCsvFiles + "entire_output.csv";
var pvQuery = from car in Cars
select car;
if (!Directory.Exists(UniversalVariables.outputCsvFiles))
{
Directory.CreateDirectory(UniversalVariables.outputCsvFiles);
}
using (var sw = new StreamWriter(_path))
using (var csv = new CsvWriter(sw))
{
csv.Configuration.Delimiter = UniversalVariables.csvDelimiter;
csv.Configuration.HasHeaderRecord = true;
csv.WriteHeader<Car>();
csv.NextRecord();
csv.WriteRecords(pvQuery);
sw.Flush();
}
You could use Linq to split the collection in to sub collections (chunks of size n). For example
pvQuery.Select((x,index)=>new {Value=x,Index=index})
.GroupBy(x=>(int)(x.Index/numberOfItemsPerGroup))
.Select(x=>x.Select(c=>c.Value));
Making it a Extension method
static class Extensions
{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int numberOfItemsPerGroup)
{
return source.Select((x,index)=>new {Value=x,Index=index})
.GroupBy(x=>(int)(x.Index/numberOfItemsPerGroup))
.Select(x=>x.Select(c=>c.Value));
}
}
Client code
SourceCollection.Split(numberOfItemsPerGroup);
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have two objects: 'Table' and 'Record'. 'Table' has a property 'Items' that is an array of type 'Record[]'.
How do I set the 'Items' property of a specific instance of 'Table' (e.g., table.Items[0]) to a specific instance of 'Record' (e.g., first_record)?
I tried to code it as follows, but my code results in a "NullReferenceException was unhandled" error.
Record first_record = new Record();
first_record.Field1 = "r1f1";
first_record.Field2 = "r1f2";
first_record.Field3 = "r1f3";
Record second_record = new Record();
second_record.Field1 = "r2f1";
second_record.Field2 = "r2f2";
second_record.Field3 = "r2f3";
Table table = new Table();
table.Items[0] = first_record;
table.Items[1] = second_record;
Thank you
Stackoverflow suggested a similar question that provided my answer. I failed to initialize the array. Here's the line I was missing:
table.Items = new Record[2];
Inserting that line into the code from my original question results in the following:
Record first_record = new Record();
first_record.Field1 = "r1f1";
first_record.Field2 = "r1f2";
first_record.Field3 = "r1f3";
Record second_record = new Record();
second_record.Field1 = "r2f1";
second_record.Field2 = "r2f2";
second_record.Field3 = "r2f3";
Table table = new Table();
table.Items = new Record[2];
table.Items[0] = first_record;
table.Items[1] = second_record;
That did the trick. Thank you Stackoverflow!
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
}
This question already has answers here:
How to save a List<string> on Settings.Default?
(4 answers)
Saving from List<T> to txt
(7 answers)
Closed 7 years ago.
I'm new to C# and I'm trying to make a List persist when relaunching the application. Everywhere I go I can't seem to find a simple way to do this, something like Python's Pickle. Any help would be appreciated thank you.
The answer to this really depends on what exactly you want to save. Is it an actual List, as in List<> obejct? What does it contain? If it's something simple such as a List< string >, then do
var list = new List<string>();
list.Add("HELLO");
list.Add("hi");
// save
using (var fs = new FileStream(#"F:\test.xml", FileMode.Create))
{
var serializer = new XmlSerializer(typeof(List<string>));
serializer.Serialize(fs, list);
}
// read
using (var s = new FileStream(#"F:\test.xml", FileMode.Open))
{
var serializer = new XmlSerializer(typeof(List<string>));
List<string> result = (List<string>)serializer.Deserialize(s);
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 10 years ago.
I need kind favor to signoff the task. I want to count the tag using htmlaglitypack. I tried to count the tag by using htmlcollection node. But getting
"Object reference not set to an instance of an object"
In the line foreach condition. Can anyone of them rectify the issue why I'm getting like that?
My code is posted below:
public void XmlPPC(string rights)
{
int count = 0;
try
{
MessageBox.Show(rights);
using (FileStream fs = File.Open(rights,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(sr);
HtmlNodeCollection right = doc.DocumentNode.SelectNodes("//copyrightLine");
foreach (HtmlNode logan in right)
{
count = count + 1;
MessageBox.Show("cnt" + count.ToString());
}
// snip...
}
}
catch (Exception f)
{
log = log + "\r\n" + f.ToString();
}
}
You're getting the error:
Object reference not set to an instance of an object.
because this line:
HtmlNodeCollection right = doc.DocumentNode.SelectNodes("//copyrightLine");
is returning null. That can only happen because there is no element named copyrightLine. Please consider the following specification for the // operation:
Selects nodes in the document from the current node that match the selection no matter where they are.
Now, the fix is one of a few things:
Get an element in there named copyrightLine.
Fix the misspelling as it could be misspelled.
Search for what you need in a different way if it doesn't fall into those two.