Count() a specfic attribute within a list c#

前端 未结 3 974
一向
一向 2021-01-28 17:32
if (gardenvlist.Count() == getava.Count())
{

}
else if(oceanvlist.Count() == getava.Count())
{

}
else if (cityvlist.Count() == getava.Count())
{

}

<

相关标签:
3条回答
  • 2021-01-28 17:46

    If I understand your question correctly, you can pass in a lambda expression to Count() to selectively count items based on properties then compare that to whatever you'd like. Something like this:

    if (gardenvlist.Count()== getava.Count(x => x.Name == "GardenName"))

    Note you will need to add the following using statement: using System.Linq

    0 讨论(0)
  • 2021-01-28 18:08

    Use the overload which takes a predicate. Here is the signature:

    public static int Count<TSource>(this IEnumerable<TSource> source, 
        Func<TSource, bool> predicate);
    

    Imaging you have this:

    public class Room
    {
        public string Name { get; set; }
    }
    

    Then you put them into a list:

    var rooms = new List<Room>()
    {
        new Room { Name = "Living" },
        new Room { Name = "Kitchen" }
    };
    

    You want to know how many rooms have the name "Living":

    int count = rooms.Count(x => x.Name == "Living");
    
    0 讨论(0)
  • 2021-01-28 18:13

    There is another overload of Count() that takes a lambda expression as a parameter where you can filter elements to count from the source collection.

    Say you have a list of strings like this:

    var list = new List<string>() {
       "a",
       "b",
       "c",
       "aa",
       "bbb"
    };
    

    Then you can use it like this:

    var countSingles = list.Count(str => str.Length == 1);
    

    This will count the elements of the list with length 1, so here it would return 3.

    0 讨论(0)
提交回复
热议问题