自动计算类中的属性

时间:2019-04-29 14:06:42

标签: c# linq

我有这两节课:

public class LeadPerformanceItem
{
    public string name { get; set; }

    public int visitors { get; set; }

    public decimal visitorspercentoftotal
    {
        get
        {
        // ?
        }
    }
}

public class LeadPerformanceItemCollection
{
    public List<LeadPerformanceItem> items {get;set;}

    public int totalvisitors
    {
        get
        {
            return items.Sum(x => x.visitors);
        }
    }       
}

无论如何,添加或从集合中删除项目时,我的Visitorspertaloftotal属性是否可以自动计算?

2 个答案:

答案 0 :(得分:1)

  public class LeadPerformanceItem
    {
        public string name { get; set; }

        public int Visitors { get; set; }

        private int _totalVisitors = 0;

        public void UpdateTotalVisitors(int total)
        {
            this._totalVisitors = total;
        }

        public decimal Visitorspercentoftotal => _totalVisitors != 0
            ? Convert.ToDecimal(Math.Round(((double) (Visitors * 100)) / _totalVisitors))
            : 0;
    }

    public class LeadPerformanceItemCollection
    {
        public List<LeadPerformanceItem> Items { get; set; }

        public void AddToItems(LeadPerformanceItem item)
        {
            Items.Add(item);
            var total = Items.Sum(x => x.Visitors);
            Items.AsParallel().ForAll(i => i.UpdateTotalVisitors(total));
        }


        public int totalvisitors
        {
            get { return Items.Sum(x => x.Visitors); }
        }
    }

    [TestFixture]
    public class Class1
    {
        [Test]
        public void Test()
        {
            var leadPerformanceItemCollection = new LeadPerformanceItemCollection();
            leadPerformanceItemCollection.Items=new List<LeadPerformanceItem>();
            leadPerformanceItemCollection.AddToItems(new LeadPerformanceItem()
            {
                name = "test",
                Visitors = 10
            });
            leadPerformanceItemCollection.AddToItems(new LeadPerformanceItem()
            {
                name = "test2",
                Visitors = 25
            });

            Console.WriteLine(leadPerformanceItemCollection.Items[0].Visitorspercentoftotal);
            Console.WriteLine(leadPerformanceItemCollection.Items[1].Visitorspercentoftotal);

        }
    }

结果:

29%
71%

答案 1 :(得分:-2)

一种方法是从List继承并隐藏Add方法,然后创建自己的方法并在那里进行计算。

public class LeadPerformanceItemCollection : List<LeadPerformanceItem>
{

    public new void Add(LeadPerformanceItem item)
    {
        //calculate percent of total here

        base.Add(item);
    }

}