I'm trying to perform data validation (null checking) on my data before database insertion. I simply want to do a foreach loop over my DB model class like so:
foreach (var item in Insert)
{
if (item.value == null)
// do something
}
I've tried a few variations of this and this but I just can't seem to get what I want. Here's what I have so far. In Main.cs
private void Form1_Load(object sender, EventArgs e)
{
try
{
var i = 0;
var Insert = new MyItems();
foreach (var item in Insert)
{
i++;
Debug.WriteLine(i + ": " + item);
if (item.value == null)
// do something
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
in Model.cs
public class MyItems : IEnumerable<MyItems>
{
List<MyItems> items = new List<MyItems>();
public IEnumerator<MyItems> GetEnumerator()
{
foreach (var item in items)
yield return item;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public string HandleUid { get; set; }
public string TestSpin { get; set; }
public string PartNumber { get; set; }
public string LotNumber { get; set; }
public string MachineName { get; set; }
// plus more items
}
I've done it this way too which yields the same results.
public class MyItemList
{
}
public class MyItems : IEnumerable<MyItemList>
{
List<MyItemList> items = new List<MyItemList>();
public IEnumerator<MyItemList> GetEnumerator()
{
return items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public string HandleUid { get; set; }
public string TestSpin { get; set; }
public string PartNumber { get; set; }
public string LotNumber { get; set; }
public string MachineName { get; set; }
//...
This is just a test program. In my real app, Insert will be populated. When I run this, Insert contains each element but if I step into the foreach loop in the MyItems class, the count is zero, which I sort of understand, but why then does Insert contain an item list? I feel like I keep getting really close to the solution but can't finish the last mile.
So instead of having to do this for many items:
if (Myitems.HandleUid.Value === null)
//do something
if (Myitems.TestSpin.Value === null)
//do something
if (Myitems.PartNumber.Value === null)
//do something
if (Myitems.LotNumber.Value === null)
//do something
if (Myitems.MachineName.Value === null)
//do something
etc...
I want to do this instead:
foreach (var item in Myitems)
{
if (item.value == null)
// do something
}
So I'm trying to add iteration to my custom class.