简体   繁体   中英

Ideal c# reduction method for values of the same type, with bitwise approach?

Good day all,

I have a class and a property, and I have three instances of that class.

public class myclass {
  public int myproperty;
}

...

myclass inst1, inst2, inst3;

...

Now at a certain point I need to compare those three property values, and verify that they be equal or not, to end up with the least amount of values.

So if I have

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

after the magic_function_call, I should get 3 and 5.

And if I have

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

after the magic_function_call, I should get 2.

Albeit this is trivial per se, and can be solved with as many IF checks as needed, I was wondering which is the fastest, or more efficient way to do it, especially in light of the fact that I might need to add another variable to the check in the future.

I am in fact wondering if there is a bitwise operation that can be performed that can solve this elegantly and quickly.

Alternatively, is there an array operation that can be used to achieve the same goal? I've tried looking for 'reduction' or 'compression' but those keywords don't seem to lead in the right direction.

Thanks in advance.

You can use the morelinq DistinctBy query operator if all of the instances belong to a collection:

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

Looking at the question, you may want a list of just the property values (a list of ints), which you can achieve with the standard query operators:

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

Note that you haven't defined a property, you've defined a public field. To define an auto property change:

public int myproperty;

to

public int myproperty { get; set; }

Note also that PascalCasing is recommended for property and class names.

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

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

Here's a quick function which doesn't require any extra libraries and avoids the setup costs and overheads associated with 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();
    }

Pass it a collection of your myclass instances and it will return an array of unique myproperty values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM