Tbooty
Tbooty

Reputation: 289

Return the number of times a string occurs as a property in a list of custom objects

I'm trying to return a list with the number of times a property has a value set.

I'm trying to do this without having to hardcode the value to look for, so if something changes on the backend I won't have to add a new line of code.

Currently I have it working, but I have set the values manually.

listCounts.Add(testList.Count(item => item.title == "Blah"));
listCounts.Add(testList.Count(item => item.title == null));
listCounts.Add(testListt.Count(item => item.title == "test"));
listCounts.Add(testList.Count(item => item.title == "Blarg"));

This works currently but if anything chaanges, i'll have to go in and made changes to the code which is what I am trying to avoid

Upvotes: 1

Views: 83

Answers (2)

David_001
David_001

Reputation: 5812

Depends on what you're trying to do really. It looks like you want the count of wach of those keys (the titles)?

One way would be to group by your title to give the counts, eg.

var listCounts = testList.GroupBy(item => item.title);

As an example of using this:

    class Item
    {
        public string title;
    }

    static void Main(string[] args)
    {
        var testList = new List<Item>
        {
            new Item { title = "Blah" },
            new Item { title = "Blah" },
            new Item { title = "Blah" },
            new Item { title = null },
            new Item { title = null },
            new Item { title = "test" },
            new Item { title = "test" },
            new Item { title = "test" },
            new Item { title = "test" }
        };


        var listCounts = testList.GroupBy(item => item.title);

        foreach (var count in listCounts)
        {
            Console.WriteLine("{0}: {1}", count.Key ?? string.Empty, count.Count());
        }

        Console.ReadKey();

    }

The disadvantage is you're getting the count each time - like I said, it depends on what you're trying to achieve. A simple change would make this a dicationary (string, int), whereby each title would be a key, and the value would be the number of times the title appears.

EDIT

To use a dictionary, change the listCounts line to:

var listCounts = testList.GroupBy(t => t.title).ToDictionary(i => i.Key ?? string.Empty, i => i.Count()); 

(note that a key cannot be null, hence the i.Key ?? string.Empty workaround, should be fine for your purposes)

Upvotes: 2

Kilazur
Kilazur

Reputation: 3188

We don't know what your backend is, but it would seem you need to retrieve the values from it.

//string[] myStrings = new string[] { "Blah", null, "test", "Blarg" };
string[] myStrings = _backEnd.RetrieveValues();
listCounts.Add(testList.Count(item => myStrings.Contains(item)));

Upvotes: 1

Related Questions