1. 程式人生 > >Linq 和 list集合 去除重複項

Linq 和 list集合 去除重複項

方法一:

IQueryable<NewsContents專案> listNotice = null;

 listNotice = (from news in base.CabinData.NewsContents where news.FLAG == 1 select news).Distinct();

此種去除方法弊端:只要物件中有重複的欄位都會去除,會比對物件中所有的欄位。

方法二:

把linq查詢結果轉成list物件集合,再過濾去除重複項

 List<NewsContents專案> list = new List<NewsContents專案>();  // NewsContents專案 為實體類model

 list = (from news in base.CabinData.NewsContents where news.FLAG == 1 select news).Distinct();

List<NewsContents專案> listNotice = list.Distinct(new item_collection_DistinctBy_item1()).ToList();

 //去除重複項
        public class item_collection_DistinctBy_item1 : IEqualityComparer<Entity.NewsContents專案>
        {
            bool IEqualityComparer<Entity.NewsContents專案>.Equals(Entity.NewsContents專案 x, Entity.NewsContents專案 y)
            {
                if (x.Id == y.Id)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

            int IEqualityComparer<Entity.NewsContents專案>.GetHashCode(Entity.NewsContents專案 obj)
            {
                return 0;
            }


        }

=================================================

終於弄出來了,和大家分享!
謝謝3樓的那位兄弟。
C# code
using System; using System.Collections.Generic;
using System.Linq; using System.Text; namespace ConsoleApplication5 { class Program { staticvoid Main(string[] args) { List<item> list =new List<item>(); list.Add(new item { item1 =1, item2 ="b", item3 =4.0,item4=8 }); list.Add(new item { item1 =1, item2 ="a", item3 =1.0 ,item4=9}); list.Add(new item { item1 =2, item2 ="a", item3 =1.0 ,item4=7}); list.Add(new item { item1 =3, item2 ="a", item3 =1.0 ,item4=6}); list.Add(new item { item1 =1, item2 ="a", item3 =2.0 ,item4=5}); List<item> temp = list.Distinct(new item_collection_DistinctBy_item1()).ToList(); foreach (var item in temp) { Console.WriteLine(item); } Console.Read(); } } class item { publicint item1 { get; set; } publicstring item2 { get; set; } publicdouble item3 { get; set; } publicint item4 { get; set; } publicoverridestring ToString() { returnstring.Format("item1:{0},item2:{1},item3:{2},item4:{3}", item1, item2, item3,item4); } } class item_collection_DistinctBy_item1 : IEqualityComparer<item> { publicbool Equals(item x, item y) { if (x.item1 == y.item1 && x.item3 == y.item3) { returntrue; } else { returnfalse; } } publicint GetHashCode(item obj) { return0; } } }