简体   繁体   中英

Counting number of items in ObservableCollection where it equals 1 - C#

I made an SQL query and filled the data to an ObservableCollection. The database contains many columns so I want to count how many instances where a specific column = 1, then return that number to an int.

The query:

var test = from x in m_dcSQL_Connection.Testheaders 
           where dtStartTime <= x.StartTime && dtEndtime >= x.StartTime 
           select new {
                         x.N, 
                         x.StartTime, 
                         x.TestTime, 
                         x.TestStatus, 
                         x.Operator, 
                         x.Login,
                         x.DUT_id, 
                         x.Tester_id, 
                         x.PrintID 
                       };

Then I add the data pulled from the database to an Observable Collection via:

lstTestData.Add(new clsTestNrData(item.N.ToString(), 
                    item.StartTime.ToString(), 
                    item.TestTime.ToString()
                    etc.....

I want to count how many times TestStatus = 1.

I have read about the .Count property but I do not fully understand how it works on ObservableCollections.

Any help?

The standard ObservableCollection<T>.Count property will give you the number of items in the collection.

What you are looking for is this:

testStatusOneItemCount = lstTestData.Where(item => item.TestStatus == 1).Count()

...which uses IEnumerable<T>.Count() method which is part of LINQ.

To elaborate a bit, Count will simply count the objects in your collection.
I suggest having a quick look at linq 101 . Very good examples.

Here's an example:

// Assuming you have :
var list = new List<int>{1,2,3,4,5,6 };
var items_in_list = list.Count(); //  = 6;

Using linq's Where , you're basically filtering out items, creating a new list. So, the following will give you the count of all the numbers which are pair:

var pair = list.Where(item => item%2 ==0);
var pair_count = pair.Count; // = 3

You can combine this without the temp variables:

var total = Enumerable.Range(1,6).Where(x => x % 2 ==0).Count(); // total = 6;

Or you can then select something else:

var squares_of_pairs = Enumerable.Range(1,6)
                                .Where(x => x % 2 ==0).
                                .Select( pair => pair*pair);
// squares_of_pairs = {4,16, 36}. You can count them, but still get 3 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM