Unique list of items using LINQ

后端 未结 6 1413
星月不相逢
星月不相逢 2021-02-01 05:39

I\'ve been using LINQ for a while now, but seem to be stuck on something with regards to Unique items, I have the folling list:

List stock = new Lis         


        
6条回答
  •  清歌不尽
    2021-02-01 05:58

    static class EnumerableEx
    {
        // Selectively skip some elements from the input sequence based on their key uniqueness.
        // If several elements share the same key value, skip all but the 1-st one.
        public static IEnumerable uniqueBy( this IEnumerable src, Func keySelecta )
        {
            HashSet res = new HashSet();
            foreach( tSource e in src )
            {
                tKey k = keySelecta( e );
                if( res.Contains( k ) )
                    continue;
                res.Add( k );
                yield return e;
            }
        }
    }
    
    // Then later in the code
    List res = src.uniqueBy( elt => elt.Type ).ToList()
    

提交回复
热议问题