c# 利用分組思想對list中的重複元素進行統計

想統計一個列表中,重複元素的個數。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 統計元素重複出現次數
{
    class Program
    {
        static void Main(string[] args)
        {
            //還是用的分組思想
            List<Pet> nums =new List<Pet> {
                new Pet{Name="abc",Age=18,Count=0 },
                new Pet{Name="abc",Age=18,Count=0 },
                new Pet{Name="abc",Age=18,Count=0 },
                new Pet{Name="abc",Age=18,Count=0 },


                new Pet{Name="Tro",Age=18,Count=0 },
                new Pet{Name="Tro",Age=18,Count=0 },
                

            };
           var r= nums.GroupBy(x => x.Name );
            foreach (var x in r)
            {
                
                foreach (var item in nums)
                {
					
                    if(item.Name==x.Key)
                    { item.Count = x.Count(); }
                }
            }
            foreach (var item in nums)
            {
                Console.WriteLine("{0}--{1}--{2}",item.Name,item.Age,item.Count);
            }
            Console.Read();

        }
    }
    class Pet
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public int Count { get; set; }
    }
}

如果是多個Key的分組 var r= nums.GroupBy(x =>new{ x.Name ,x.Age});
兩次迭代,把分組的統計個數添加回原列表。

在這裏插入圖片描述
下一步可以考慮去重。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章