'LINQ expression duplicates values on select instead of cycling them
I have a class to store some info about the files contained in folder:
static class fileList
{
public static IEnumerable<files> fL;
}
public class files
{
private static string _name = "";
private static long _size;
private static DateTime _creationDate;
public string name
{
get { return _name; }
set { _name = value; }
}
public long size
{
get { return _size; }
set { _size = value; }
}
public DateTime creationDate
{
get { return _creationDate; }
set { _creationDate = value; }
}
}
the files list is then populated via:
fileList.fL = Directory.EnumerateFiles(folder, "*.*", SearchOption.AllDirectories)
.Select(x => new
{
name = x.ToString(),
size = new FileInfo(x).Length,
creationDate = new FileInfo(x).CreationTime
});
Now the returned structure will be an IEnumerable of the (example) 3 files in the folder.
Up until this point everything is working. The problem raises when i try to return a declared type and not an anonymous one
var fL = Directory.EnumerateFiles(folder, "*.*", SearchOption.AllDirectories);
fileList.fL = fL.Select(x => new files()
{
name = x.ToString(),
size = new FileInfo(x).Length,
creationDate = new FileInfo(x).CreationTime
});
This will return 3 IEnumerable items but all of them containing the exact same info. Which as far I can see is the last file entry returned by the EnumerateFiles method.
The reason why I would like to return a type is because these info then will go into a DataGridView and if the data source is an anonymous type it will be not possible to perform any changes since the type is ReadOnly.
Solution 1:[1]
You seem to not fully unserstand what the static-modifier is about. In short it is used when a member belongs to all instances of a class, whereas non-static means that every instance of your class (whenever you write new files()) has its own values for the member. In your case the static results in all instances of your class having the same values, those from the last iteration of your fileList.Fl-collection. You may also have a further look on the MSDN for static.
Having said this your problem is resolved by removing the static-modifier from your backing-fields as others alrready mentioned.
Apart from this you should read about naming-conventions, e.g. class-names being written in CamelCase - for example class Files instead of files or even better - as actually every instance of your class represents one single file, just use File. Similary rename fileList to FileList and all your public members to CamelCase as well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
