Umar Faraz
Umar Faraz

Reputation: 3

how can read the value dynamically from array of objects and count it?

enter image description here

provider is my doctor and every doctor has patient test now I want to count unique test name and its reading of very test type. test name is repeating but I want to unique and its reading count

        var criticalReading = new ProviderBL().GetCriticalReadingByProvider(userid);
        CriticalReadingListViewModel obj = new CriticalReadingListViewModel();
        int D = 0;
        int S = 0;
        int u = 0;
        foreach (var item in criticalReading)
        {

            if (item.AttributeName == "Systolic")
            {
                obj.Dcounter = S;
                S++;
            }
            else if (item.AttributeName == "Diastolic")
            {
                obj.Scounter = D;
                D++;
            }
            else
            {
                u++;
            }

        }

Upvotes: 0

Views: 313

Answers (2)

Caius Jard
Caius Jard

Reputation: 74710

To uniquely count something and retain the original data too, you can use a Dictionary<string, List<int>>

var d = new Dictionary<string, List<int>>();
foreach(Test t in tests)
{
  if(!d.ContainsKey(t.AttributeName))
    d[t.AttributeName] = new List<int>();

  d[t.AttributeName].Add(t.Reading);
}

You now have a dictionary with one entry per test attribute name. Each dictionary entry value is a list of ints that are the readings. Thus d.Count is the number of unique tests

If you want more information out of the test it might be better to retain the whole test object in the dictionary value rather than just the Reading

You can also use LINQ to create such a dictionary:

var d = tests.GroupBy(k => k.AttributeName, v => v.Reading).ToDictionary(g =>g.Key, g=>g.ToList());

Upvotes: 0

T.S.
T.S.

Reputation: 19394

From what I see in your code, this may be the answer

var systolicCount = array.Count(item => item.AttributeName == "Systolic");
var diastolicCount = array.Count(item => item.AttributeName == "Diastolic");

These are LINQ lambda methods that will count number of items having certain attribute

Upvotes: 2

Related Questions