0

I have Collection:

    public class Test
    {
        public double Index { set; get; }
        public double A { set; get; }
        public double B { set; get; }
        public double C { set; get; }
    }
    List<Test> test = new List<Test>();

I filled A and B with some random numbers. After that, I want add items C in collection. For example, what I trying:

        foreach (Test t in test)
        {
            c = t.A + t.B;
            test.Add(new Test {C = c }); <------ 
        }

How can I add element C on same position like A and B? (Sorry for my english)

Revolt
  • 89
  • 1
  • 9
  • 9
    The "items" of the collection already have a `C` property, as such it seems what you want to do is this: `foreach (Test t in test) { t.C = t.A + t.B; }`, can you verify if this is what you want? – Lasse V. Karlsen Oct 28 '16 at 13:55
  • Only one element can be in one position. You can Insert(index, item) instead od Adding, though. – TaW Oct 28 '16 at 13:55
  • 1
    Just saying (as I don't really get what you are trying to do anyway so it might be something to consider for you)... `public double C { get { return A + B; } }` – musefan Oct 28 '16 at 13:57
  • @LasseV.Karlsen Yes it is ... It was simple, lol ... Sometimes I thinking very hard way... Thank you very much – Revolt Oct 28 '16 at 13:57
  • 2
    Please take a look at the answer that has been posted, it may be that that is an even better solution. – Lasse V. Karlsen Oct 28 '16 at 13:59

2 Answers2

3

If you want C to be the sum of A and B it might be better to use a computed field:

public class Test
{
    public double Index { set; get; }
    public double A { set; get; }
    public double B { set; get; }
    public double C 
    { 
       get
       {
            return A + B;
       } 
    }
}

So

Test test = new Test()
{
   A = 1;
   B = 2;
};

test.C == 3; //true

the advantage of the above is that C is always the sum of the other values and you don't need to recompute it every time. So if I take above and do:

test.B = 3; //instead of the original 2

Then C stays in sync:

test.C == 3; //false
test.C == 4; //now true

To do this with your original method (or the other answer) means re-looping the result set.

Or in C# 6.0 you can use an expression-bodied property

public class Test
{
    public double Index { set; get; }
    public double A { set; get; }
    public double B { set; get; }
    public double C =>  A + B;
}
Community
  • 1
  • 1
Liam
  • 27,717
  • 28
  • 128
  • 190
2
foreach (Test t in test)
{
    t.C = t.A + t.B;
} 

just set the property to the equation

Liam
  • 27,717
  • 28
  • 128
  • 190
M B
  • 2,326
  • 24
  • 33