C# Class/Object passing (Array of Objects)

时间:2017-04-24 17:20:08

标签: c# arrays object

Right so i have a class I'm using to store a set of values

public class dataSet
 {
  public int Number;
  public double Decimal;
  public string Text;
  //etc...
 }

Then I've made an array of type dataSet

public static dataSet[] dataOne = new dataSet[100];

And i'm trying to sort the array of dataOne relevant to the values stored in the int Number stored within dataSet. I have a sort algorithm ready but i'm struggling to pass in the values stored solely in dataOne.Number so it just ends up being an integer array that i'm passing to the sort. I'm a total noob at programming so any help would be greatly appreciated.

Edit:

I need to call my sort function by passing it in the array of dataOne.Number if this is possible? So it's basically just passing the sort function an int[]

3 个答案:

答案 0 :(得分:3)

Give you already have data into your array named dataOne, you could try:

Linq Solution

Use linq to sort it, try this:

dataOne = dataOne.OrderBy(x => x.Number).ToArray();

Remember to add the namespace System.Linq to have access into these methods.

OrderBy allows you to pass an expression to sort data and it will return an IOrderedEnumerable. The ToArray will convert it to an array.

Not Linq Solution

If you are not allowed to use Linq. You could implement an class that implements IComparer<T> and implement the method Compare which takes two generics arguments. Use an instance of this comparer type to sort your data.

For sample, since you have your dataSet type defined, you could implement the comparer:

public class DataSetComparer : IComparer<dataSet>
{
    public int Compare(dataSet x, dataSet y)
    {
        // define the logic to sort here...
        return x.Number.CompareTo(y.Number);
    }
}

And then, use the comparer on the Array.Sort method:

Array.Sort(dataSet, new NumberComparer());

It will order your dataSets.

答案 1 :(得分:0)

I'm not sure I follow why you can't use Linq. But that forces you do to something like this:

var numberValues = new List<int>();
foreach(var dataItem in dataOne)
{
    numberValues.Add(dataItem.Number);
}

Then you could pass numberValues.ToArray() to your sort method.

With Linq it would just be

dataOne.Select(d => d.Number).ToArray()

答案 2 :(得分:0)

你应该让数据集实现IComparable,就像你可以轻松做到的那样......

dataOne = dataOne.OrderBy(x => x).ToArray();

... OR

Array.Sort(dataOne);

以下是如何实现IComparable ......

public class dataSet : IComparable
{
    public int Number;
    public double Decimal;
    public string Text;

    public int CompareTo(object obj)
    {
        if (obj == null)
            return 1;
        dataSet other = obj as dataSet;
        if (other != null) 
            return this.Number.CompareTo(other.Number);
        else
            throw new ArgumentException("Object is not a dataSet");
    }
}