簡體   English   中英

在列表C#中搜索特定的重復鍵

[英]Search Specific Duplicated keys in List C#

我有一個名為“ listA”的列表包含1個名為“ fieldA”的字段,數據為

{1,0,0,0,1}

我只想檢測“ 1”中是否存在重復項,但是如果重復“ 0”,則不會算作重復項

我嘗試

 var dupl = listA
                            .GroupBy(i => i.fieldA=="1")
                            .Where(g => g.Count() > 1)
                            .Select(g => g.Key).ToList();
 if (dupl.Count()>0){"you have duplicated 1"}

但是仍然檢測到“ 0”重復,我的linq怎么了?

如果您只想知道是否存在1的重復項,則只需使用Count

bool isDuplicate = listA.Count(x => x.fieldA == "1") > 1;

您可以嘗試以下方法:

bool oneIsDuplicate = listA.Where(x=>x.fieldA=="1").Count() > 1;

這可能會有所幫助。 在這里我們避免了在達到集合結束之前滿足條件的情況下進行額外的迭代。(如果情況在集合結束之前得到滿足,我們不會對整個集合進行迭代,因此可以提高性能明智的)。

public static class Extentions
    {
        /// <summary>
        /// Used to find if an local variable aggreation based condition is met in a collection of items.
        /// </summary>
        /// <typeparam name="TItem">Collection items' type.</typeparam>
        /// <typeparam name="TLocal">Local variable's type.</typeparam>
        /// <param name="source">Inspected collection of items.</param>
        /// <param name="initializeLocalVar">Returns local variale initial value.</param>
        /// <param name="changeSeed">Returns desired local variable after each iteration.</param>
        /// <param name="stopCondition">Prediate to stop the method execution if collection hasn't reached last item.</param>
        /// <returns>Was stop condition reached before last item in collection was reached.</returns>
        /// <example> 
        ///  var numbers = new []{1,2,3};
        ///  bool isConditionMet = numbers.CheckForLocalVarAggreatedCondition(
        ///                                             () => 0, // init
        ///                                             (a, i) => i == 1 ? ++a : a, // change local var if condition is met 
        ///                                             (a) => a > 1);   
        /// </example>
        public static bool CheckForLocalVarAggreatedCondition<TItem, TLocal>(
                                this IEnumerable<TItem> source,
                                Func<TLocal> initializeLocalVar,
                                Func<TLocal, TItem, TLocal> changeSeed,
                                Func<TLocal, bool> stopCondition)
        {
            TLocal local = default(TLocal);
            foreach (TItem item in source)
            {
                local = changeSeed(local, item);
                if (stopCondition(local))
                {
                    return true;
                }
            }

            return false;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM