使用 LINQ,我可以验证所有对象的属性都具有相同的值吗?

发布于 2024-10-27 18:21:25 字数 780 浏览 1 评论 0原文

我有一个 Crate 对象,其中有一个 KeyValuePairs 列表。目前,我正在迭代每一对,以查看列表中所有项目的 kvp.Value.PixelsWide 是否相同。如果是,则返回 true,否则返回 false。

我现有的方法如下所示:

public bool Validate(Crate crate)
    {
        int firstSectionWidth = 0;
        foreach (KeyValuePair<string, SectionConfiguration> kvp in crate.Sections)
        {
            if (firstSectionWidth == 0)//first time in loop
            {
                firstSectionWidth = kvp.Value.PixelsWide;
            }
            else //not the first time in loop
            {
                if (kvp.Value.PixelsWide != firstSectionWidth)
                {
                    return false;
                }
            }
        }

        return true;
    }

我很好奇这是否可以在 LINQ 查询中执行?

预先感谢您的任何帮助!

I have a Crate object, which has a List of KeyValuePairs. Currently, I'm iterating through each pair to see if the kvp.Value.PixelsWide are the same for all items in the List. If they are, return true, else false.

The existing method that I have is shown below:

public bool Validate(Crate crate)
    {
        int firstSectionWidth = 0;
        foreach (KeyValuePair<string, SectionConfiguration> kvp in crate.Sections)
        {
            if (firstSectionWidth == 0)//first time in loop
            {
                firstSectionWidth = kvp.Value.PixelsWide;
            }
            else //not the first time in loop
            {
                if (kvp.Value.PixelsWide != firstSectionWidth)
                {
                    return false;
                }
            }
        }

        return true;
    }

I'm curious if this would be possible to execute in a LINQ query?

Thanks in advance for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

メ斷腸人バ 2024-11-03 18:21:25

我相信这会起作用:

public bool Validate(Crate crate)
{
    return crate.Sections
                .Select(x => x.Value.PixelsWide)
                .Distinct()
                .Count() < 2;
}

如果 crate.Sections 为空以及元素全部相同(这是当前函数的行为),这将返回 true。

I believe this would work:

public bool Validate(Crate crate)
{
    return crate.Sections
                .Select(x => x.Value.PixelsWide)
                .Distinct()
                .Count() < 2;
}

This will return true if crate.Sections is empty as well as when the elements are all the same (which is the behavior of your current function).

三岁铭 2024-11-03 18:21:25

试试这个

var pixelsWide = rate.Sections.Values.First().PixelsWide;
bool result = crate.Sections.Values.All(x => x.PixelsWide == pixelsWide);

Try this

var pixelsWide = rate.Sections.Values.First().PixelsWide;
bool result = crate.Sections.Values.All(x => x.PixelsWide == pixelsWide);
治碍 2024-11-03 18:21:25

这是 Stecya 的 答案不会为空集合引发异常。

var first = crate.Sections.Values.FirstOrDefault();
bool result = crate.Sections.Values.All(x => x.PixelsWide == first.PixelsWide);

Here's a variation on Stecya's answer that doesn't throw an exception for an empty collection.

var first = crate.Sections.Values.FirstOrDefault();
bool result = crate.Sections.Values.All(x => x.PixelsWide == first.PixelsWide);
┈┾☆殇 2024-11-03 18:21:25

如果您不介意迭代整个集合:

bool hasOneValue = crate.Sections.Select(s => s.Value.PixelsWide).Distinct().Count() == 1;

或者使其与您的代码一致:

bool validateResult = crate.Sections.Select(s => s.Value.PixelsWide).Distinct().Count() <= 1;

If you don't mind iterating through entire collection:

bool hasOneValue = crate.Sections.Select(s => s.Value.PixelsWide).Distinct().Count() == 1;

Or making it consistent with your code:

bool validateResult = crate.Sections.Select(s => s.Value.PixelsWide).Distinct().Count() <= 1;
苯莒 2024-11-03 18:21:25

分组太慢了吗?

public bool Validate(Crate crate)
{
    return crate.GroupBy(c => c.Value.PixelsWide).Count() < 2;
}

Is grouping too slow?

public bool Validate(Crate crate)
{
    return crate.GroupBy(c => c.Value.PixelsWide).Count() < 2;
}
柏林苍穹下 2024-11-03 18:21:25

我和@Stecya 在一起:

public class Crate
{
    IList<KeyValuePair<string,SectionConfiguration>> Sections ;

    public bool IsValid()
    {
        return Sections.All( x => x.Value.PixelsWide == Sections.FirstOrDefault().Value.PixelsWide ) ;
    }

    public class SectionConfiguration
    {
        public int PixelsWide ;
    }

}

I'm with @Stecya:

public class Crate
{
    IList<KeyValuePair<string,SectionConfiguration>> Sections ;

    public bool IsValid()
    {
        return Sections.All( x => x.Value.PixelsWide == Sections.FirstOrDefault().Value.PixelsWide ) ;
    }

    public class SectionConfiguration
    {
        public int PixelsWide ;
    }

}
蓦然回首 2024-11-03 18:21:25

我的版本:

public bool Validate(Crate crate)
{
    return !crate.Sections
           .Any(a => crate.Sections
                     .Where(b => b.Value.PixelsWide != a.Value.PixelsWide).Any()
           );
}

My version:

public bool Validate(Crate crate)
{
    return !crate.Sections
           .Any(a => crate.Sections
                     .Where(b => b.Value.PixelsWide != a.Value.PixelsWide).Any()
           );
}
一张白纸 2024-11-03 18:21:25

这可以相当简单地实现为扩展方法:

public static bool AllEqual<T1, T2>(this IEnumerable<T1> enumerable, Func<T1, T2> selector)
{
    using (var enumerator = enumerable.GetEnumerator())
    {
        if (!enumerator.MoveNext())
            return false;

        var first = selector(enumerator.Current);
        while (enumerator.MoveNext())
        {
            var current = selector(enumerator.Current);
            if (current == null)
            {
                if (first == null)
                    continue;

                return false;
            }

            if (current.Equals(first) == false)
                return false;
        }

        return true;
    }
}

This can be implemented as an extension method fairly trivially:

public static bool AllEqual<T1, T2>(this IEnumerable<T1> enumerable, Func<T1, T2> selector)
{
    using (var enumerator = enumerable.GetEnumerator())
    {
        if (!enumerator.MoveNext())
            return false;

        var first = selector(enumerator.Current);
        while (enumerator.MoveNext())
        {
            var current = selector(enumerator.Current);
            if (current == null)
            {
                if (first == null)
                    continue;

                return false;
            }

            if (current.Equals(first) == false)
                return false;
        }

        return true;
    }
}
嘿看小鸭子会跑 2024-11-03 18:21:25

我的扩展方法如下所示:

public static bool AllAre<T>(this IList<T> self, Func<T, T, bool> predicate)
{
    if (self.Count == 0)
    {
        return true;
    }
    var first = self.First();
    return self.All(arg => predicate(arg, first));
}

并且使用方式如下:

myList.AllAre((x, first) => x.Value == first.Value);

My extension method for this looks like this:

public static bool AllAre<T>(this IList<T> self, Func<T, T, bool> predicate)
{
    if (self.Count == 0)
    {
        return true;
    }
    var first = self.First();
    return self.All(arg => predicate(arg, first));
}

And it is used like this:

myList.AllAre((x, first) => x.Value == first.Value);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文