Get Non-Distinct elements from an IEnumerable

前端 未结 4 1457
心在旅途
心在旅途 2021-02-13 13:18

I have a class called Item. Item has an identifier property called ItemCode which is a string. I would like to get a list of all non-distinct Items in a list of Items.

E

相关标签:
4条回答
  • 2021-02-13 13:47

    I'd suggest writing a custom extension method, something like this:

    static class RepeatedExtension
    {
        public static IEnumerable<T> Repeated<T>(this IEnumerable<T> source)
        {
            var distinct = new Dictionary<T, int>();
            foreach (var item in source)
            {
                if (!distinct.ContainsKey(item))
                    distinct.Add(item, 1);
                else
                {
                    if (distinct[item]++ == 1) // only yield items on first repeated occurence
                        yield return item;
                }                    
            }
        }
    }
    

    You also need to override Equals() method for your Item class, so that items are correctly compared by their code.

    0 讨论(0)
  • 2021-02-13 13:54

    as an extension method:

    public static IEnumerable<T> NonDistinct<T, TKey> (this IEnumerable<T> source, Func<T, TKey> keySelector)
    {
       return source.GroupBy(keySelector).Where(g => g.Count() > 1).SelectMany(r => r);
    }
    
    0 讨论(0)
  • 2021-02-13 14:08

    My take:

    var distinctItems = 
        from list in itemsList
        group list by list.ItemCode into grouped
        where grouped.Count() > 1
        select grouped;
    
    0 讨论(0)
  • 2021-02-13 14:09

    You might want to try it with group by operator. The idea would be to group them by the ItemCode and taking the groups with more than one member, something like :

    var grouped = from i in itemList
                  group i by i.ItemCode into g
                  select new { Code = g.Key, Items = g };
    
    var result = from g in grouped 
                 where g.Items.Count() > 1;
    
    0 讨论(0)
提交回复
热议问题