我的名单是" 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出了什么问题?
答案 0 :(得分:2)
如果您只想知道是否有重复的1,那么只需使用Count
:
bool isDuplicate = listA.Count(x => x.fieldA == "1") > 1;
答案 1 :(得分:0)
你可以尝试这个:
bool oneIsDuplicate = listA.Where(x=>x.fieldA=="1").Count() > 1;
答案 2 :(得分:0)
这个可能会有所帮助。 在达到集合结束之前满足条件时,我们避免了额外的迭代。(如果在集合结束之前满足条件,我们不会迭代整个集合,因此它会更多一些 明智地调整了表现)。
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;
}
}