Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# class object overwrite

I am new to OOP, so please take this into consideration. I am puting data that I get from this match into object of a class, but it is done in foreach loop so each time it is called, data inside my object are overwriten, and at the end I would like to have all data in my object. But I only have from last match. How should I do it to avoid this overwriting? Maybe I do it in completely wrong way?

foreach (var match in matches)
            {
                dataTable.Rows.Add(new Group[] { match.Groups["C0"], match.Groups["C1"], match.Groups["C2"], match.Groups["C3"], match.Groups["C4"] });

                MyClass sk = new MyClass();

                sk.Category = match.Groups["C0"].ToString();
                sk.Device = match.Groups["C1"].ToString();
                sk.Data_Type = match.Groups["C2"].ToString();
                sk.Value = match.Groups["C3"].ToString();
                sk.Status = match.Groups["C4"].ToString();
            }
like image 381
Michał Pastuszka Avatar asked Apr 12 '26 05:04

Michał Pastuszka


1 Answers

Create a list:

var list = new List<MyClass>();
foreach (var match in matches)
{
    dataTable.Rows.Add(new Group[] { match.Groups["C0"], match.Groups["C1"],
        match.Groups["C2"], match.Groups["C3"], match.Groups["C4"] });

    var sk = new MyClass {
        Category = match.Groups["C0"].ToString(),
        Device = match.Groups["C1"].ToString(),
        Data_Type = match.Groups["C2"].ToString(),
        Value = match.Groups["C3"].ToString(),
        Status = match.Groups["C4"].ToString()
    };
    list.Add(sk);
}

then you have all the items in the list. You could also use LINQ, for example:

var items = from match in matches
            select new MyClass {
                Category = match.Groups["C0"].ToString(),
                Device = match.Groups["C1"].ToString(),
                Data_Type = match.Groups["C2"].ToString(),
                Value = match.Groups["C3"].ToString(),
                Status = match.Groups["C4"].ToString()
            };

and iterate over items.

like image 131
Marc Gravell Avatar answered Apr 14 '26 20:04

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!