I’ve been having trouble (again) with some object-oriented code.
Currently I have a piece of code that populates a list with objects and its properties that goes like this:
foreach (var folder in pathList)
{
DirectoryInfo di = new DirectoryInfo(folder);
foreach (var file in di.GetFiles())
{
fileinfoList.Add(new FileInfo()
{
partNumber = Path.GetFileNameWithoutExtension(Convert.ToString(file)),
fileType = Path.GetExtension(Convert.ToString(file)),
lastDate = file.LastWriteTime,
released = 1,
checkedBy = null,
fullPath = Path.GetFullPath(Convert.ToString(folder)),
});
}
}
What I need is to add the baseID property to each of the objects. This is what I have currently:
foreach (var item in fileNameList)
{
if (fileinfoList.Select(m => m.partNumber == dummyString.ToString()) != null)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"data source = MYPCSQLEXPRESS; database = MYDB; integrated security = TRUE";
string query = $@"SELECT id FROM MYTABLE WHERE fullpath= '{pathsToFilesNotOnDbList[y]}' ";
var cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
iD = Convert.ToInt16(dataReader["id"]);
fileinfoList.Select (f => f.baseID = iD) ;
Console.WriteLine(y);
y++;
}
conn.Close();
}
}
I want this loop to take the value of iD and assign it to the baseID property.
I can get the iD‘s just fine, however I’m aware that the lambda expression fileinfoList.Select (f => f.baseID = iD) does nothing currently.
Can someone help me out?
Advertisement
Answer
If you want to set baseId = iD to all the elements of the list fileinfoList, just use:
fileinfoList.ForEach(i => i.baseID = iD);
UPDATE: set different id to each element:
var index = 0;
while (dataReader.Read())
{
iD = Convert.ToInt16(dataReader["id"]);
fileinfoList[index].baseID = id;
Console.WriteLine(y);
y++;
index++;
}