对于相同类型的值,采用逐位方法的理想c#缩减方法



大家好,

我有一个类和一个属性,并且我有该类的三个实例。

public class myclass {
  public int myproperty;
}
...
myclass inst1, inst2, inst3;
...

现在,在某一点上,我需要比较这三个属性值,并验证它们是否相等,以获得最少的值。

所以如果我有

inst1.myproperty = 3;
inst2.myproperty = 5;
inst3.myproperty = 3;

在magic_function_call之后,我应该得到3和5。

如果我有

inst1.myproperty = 2;
inst2.myproperty = 2;
inst3.myproperty = 2;

在magic_function_call之后,我应该得到2。

尽管这本身是微不足道的,并且可以通过所需的任意多个IF检查来解决,但我想知道哪种方法是最快或更有效的,特别是考虑到我将来可能需要在检查中添加另一个变量。

事实上,我想知道是否有一种比特操作可以优雅而快速地解决这个问题。

或者,是否有可以用于实现相同目标的数组操作?我试着寻找"减少"或"压缩",但这些关键词似乎没有指向正确的方向。

提前谢谢。

如果所有实例都属于一个集合,则可以使用morelinq DistinctBy查询运算符:

List<MyClass> myList = new List<MyClass>();
.. populate list
List<MyClass> distinct = myList.DistinctBy(mc => mc.myproperty).ToList();

考虑到这个问题,您可能想要一个仅包含属性值的列表(int列表),这可以通过标准查询运算符实现:

List<int> distinct = myList.Select(mc => mc.myproperty).Distinct().ToList();

请注意,您还没有定义属性,而是定义了一个公共字段。定义自动特性更改:

public int myproperty;

public int myproperty { get; set; }

还请注意,建议将PascalCasing用于属性和类名。

这里有一个快速函数,它不需要任何额外的库,并避免了与LINQ相关的安装成本和开销:

    static int[] Reduce(IEnumerable<myclass> items)
    {
        HashSet<int> uniqueValues = new HashSet<int>();
        foreach (var item in items)
        {
            uniqueValues.Add(item.myproperty);
        }
        return uniqueValues.ToArray();
    }

将myclass实例的集合传递给它,它将返回一个唯一的myproperty值数组。

只是实现它的另一种方法。

var result = myList.GroupBy(p => p.myproperty).Select(p => p.First());

最新更新