1

My xml:

  <Configuration>
    <LaunchDebugger>false</LaunchDebugger>
    <RequestFolder>./Request</RequestFolder>
    <ResponseFolder>./Response</ResponseFolder>
    <Countries>
      <Country NumericCode="1FH" FileName="file1.xml">1</Country>
      <Country NumericCode="20H" FileName="file2.xml">2</Country>
      <Country NumericCode="" FileName="file3.xml">3</Country>
    </Countries>
  </Configuration>

Country class:

public class Country
{
    public String Name { get; set; }
    public String NumericCode { get; set; }
    public String FileName { get; set; }
}

This is how i create objects from it using LINQ:

    CountryList = (from filter in Configuration.Descendants("Countries").Descendants("Country")
                    select new Country() 
                    {
                        Name = (string)filter.Value,
                        NumericCode = (string)filter.Attribute("NumericCode"),
                        FileName = (string)filter.Attribute("FileName")
                    }).ToList();

Parsing xml works, i get all 3 countries in my list, but i also get one extra null object as the last item of the list.

enter image description here

Any idea why that would be happening?

hs2d
  • 6,027
  • 24
  • 64
  • 103
  • 1
    You don't need to coerce `filter.Value` to `string`; it's enough to coerce `filter` alone - `(string)filter` (see [here](http://msdn.microsoft.com/en-us/library/bb387049.aspx)). – Zev Spitz Dec 06 '12 at 08:49

2 Answers2

4

Reason is simple - List<T> has default capacity equal to 4. Capacity gets or sets the total number of elements the internal data structure can hold without resizing. Internal data structure is a simple array private Country[] _items, which is initially has length equal to 4. Thus there is reserved place for forth element, which is null until element assigned. But don't worry - elements count will be 3 if you check.

Here is an image, which shows both public (three items) and internal data structure (array of capacity size)

Internal structure of List

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

We can use the TrimExcess method to reduce the capacity to match the count, but this don't work if you have less than 4 elements, like in current question.

Related links:
Capasity method - http://msdn.microsoft.com/en-us/library/y52x03h2(v=vs.100).aspx
TrimExcess method - http://msdn.microsoft.com/en-us/library/ms132207(v=vs.100).aspx
Question about default capacity - Default Capacity of List

Community
  • 1
  • 1
Juri
  • 11
  • 1