VB.Net DataTable.Select - 排序表达式语法

时间:2017-04-08 14:12:15

标签: vb.net sorting datatable

我需要从DataTable中选择行并按“Field1 / Field2”

对它们进行排序

我试过这段代码:

package cct.mad.lab;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Time;
import java.util.Calendar;

public class SettingsActivity extends Activity {

private String DEBUG_TAG;
public final static String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_NICKNAME = "Nickname"; // String
public final static String GAME_PREFERENCES_EMAIL = "Email"; // String
public final static String GAME_PREFERENCES_PASSWORD = "Password"; //String
public final static String GAME_PREFERENCES_DOB = "DOB"; // Long
public final static String GAME_PREFERENCES_GENDER = "Gender"; // Int

SharedPreferences mGameSettings;
static final int DATE_DIALOG_ID = 0;
static final int PASSWORD_DIALOG_ID = 1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settings);
    // Retrieve the shared preferences
    mGameSettings = getSharedPreferences((String) GAME_PREFERENCES, Context.MODE_PRIVATE);
    // Initialize the nickname entry
    initNicknameEntry();
    // Initialize the email entry
    initEmailEntry();
    // Initialize the Password chooser
    initPasswordChooser();
    // Initialize the Date picker
    initDatePicker();
    // Initialize the spinner
    initGenderSpinner();






}

@Override
protected void onDestroy() {
    Log.d(DEBUG_TAG, "SHARED PREFERENCES");
    Log.d(DEBUG_TAG, "Nickname is: " + mGameSettings.getString((String) GAME_PREFERENCES_NICKNAME, "Not set"));
    Log.d(DEBUG_TAG, "Email is: " + mGameSettings.getString((String) GAME_PREFERENCES_EMAIL, "Not set"));
    Log.d(DEBUG_TAG, "Gender (M=1, F=2, U=0) is: " + mGameSettings.getInt((String) GAME_PREFERENCES_GENDER, 0));
    // We are not saving the password yet
    Log.d(DEBUG_TAG, "Password is: " + mGameSettings.getString((String) GAME_PREFERENCES_PASSWORD, "Not set"));
    // We are not saving the date of birth yet
    Log.d(DEBUG_TAG, "DOB is: "
            + DateFormat.format("MMMM dd, yyyy", mGameSettings.getLong((String) GAME_PREFERENCES_DOB, 0)));
    super.onDestroy();
}

private void initNicknameEntry() {
    // Save Nickname
    final EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
    if (mGameSettings.contains((String) GAME_PREFERENCES_NICKNAME)) {
        nicknameText.setText(mGameSettings.getString((String) GAME_PREFERENCES_NICKNAME, ""));
    }
    nicknameText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                String strNickname = nicknameText.getText().toString();
                Editor editor = mGameSettings.edit();
                editor.putString((String) GAME_PREFERENCES_NICKNAME, strNickname);
                editor.commit();
                return true;
            }
            return false;
        }
    });
}

/**
 * Initialize the email entry
 */
private void initEmailEntry() {
    // Save Email
    final EditText emailText = (EditText) findViewById(R.id.EditText_Email);
    if (mGameSettings.contains((String) GAME_PREFERENCES_EMAIL)) {
        emailText.setText(mGameSettings.getString((String) GAME_PREFERENCES_EMAIL, ""));
    }
    emailText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                Editor editor = mGameSettings.edit();
                editor.putString((String) GAME_PREFERENCES_EMAIL, emailText.getText().toString());
                editor.commit();
                return true;
            }
            return false;
        }
    });
}

/**
 * Initialize the Password chooser
 */
private void initPasswordChooser() {
    // Set password info
    TextView passwordInfo = (TextView) findViewById(R.id.TextView_Password_Info);
    if (mGameSettings.contains((String) GAME_PREFERENCES_PASSWORD)) {
        passwordInfo.setText(R.string.settings_pwd_set);
    } else {
        passwordInfo.setText(R.string.settings_pwd_not_set);
    }
    // Handle password setting dialog
    Button setPassword = (Button) findViewById(R.id.Button_Password);
    setPassword.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(SettingsActivity.this, "TODO: Launch Password Dialog", Toast.LENGTH_LONG).show();
        }
    });
}

/**
 * Initialize the Date picker
 */
private void initDatePicker() {
    // Set password info
    TextView dobInfo = (TextView) findViewById(R.id.TextView_DOB_Info);
    if (mGameSettings.contains((String) GAME_PREFERENCES_DOB)) {
        dobInfo.setText(DateFormat.format("MMMM dd, yyyy", mGameSettings.getLong((String) GAME_PREFERENCES_DOB, 0)));
    } else {
        dobInfo.setText(R.string.settings_dob_not_set);
    }
    // Handle date picking dialog
    Button pickDate = (Button) findViewById(R.id.Button_DOB);
    pickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(SettingsActivity.this, "TODO: Launch DatePickerDialog", Toast.LENGTH_LONG).show();
        }
    });
}

/**
 * Initialize the spinner
 */
private void initGenderSpinner() {
    // Populate Spinner control with genders
    final Spinner spinner = (Spinner) findViewById(R.id.Spinner_Gender);
    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this, R.array.genders,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    if (mGameSettings.contains((String) GAME_PREFERENCES_GENDER)) {
        spinner.setSelection(mGameSettings.getInt((String) GAME_PREFERENCES_GENDER, 0));
    }
    // Handle spinner selections
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View itemSelected, int selectedItemPosition,
                                   long selectedId) {
            Editor editor = mGameSettings.edit();
            editor.putInt((String) GAME_PREFERENCES_GENDER, selectedItemPosition);
            editor.commit();
        }

        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DATE_DIALOG_ID:
            final TextView dob = (TextView) findViewById(R.id.TextView_DOB_Info);
            DatePickerDialog dateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    Time dateOfBirth = new Time();
                    dateOfBirth.set(dayOfMonth, monthOfYear, year);
                    long dtDob = dateOfBirth.toMillis(true);
                    dob.setText(DateFormat.format("MMMM dd, yyyy", dtDob));
                    Editor editor = mGameSettings.edit();
                    editor.putLong(GAME_PREFERENCES_DOB, dtDob);
                    editor.commit();
                }
            }, 0, 0, 0);
            return dateDialog;
        case PASSWORD_DIALOG_ID:
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View layout = inflater.inflate(R.layout.password_dialog, (ViewGroup) findViewById(R.id.root));
            final EditText p1 = (EditText) layout.findViewById(R.id.EditText_Pwd1);
            final EditText p2 = (EditText) layout.findViewById(R.id.EditText_Pwd2);
            final TextView error = (TextView) layout.findViewById(R.id.TextView_PwdProblem);
            p2.addTextChangedListener(new TextWatcher() {
                @Override
                public void afterTextChanged(Editable s) {
                    String strPass1 = p1.getText().toString();
                    String strPass2 = p2.getText().toString();
                    if (strPass1.equals(strPass2)) {
                        error.setText(R.string.settings_pwd_equal);
                    } else {
                        error.setText(R.string.settings_pwd_not_equal);
                    }
                }

                // ... other required overrides do nothing
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setView(layout);
            // Now configure the AlertDialog
            builder.setTitle(R.string.settings_button_pwd);
            builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // We forcefully dismiss and remove the Dialog, so it
                    // cannot be used again (no cached info)
                    SettingsActivity.this.removeDialog(PASSWORD_DIALOG_ID);
                }
            });
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    TextView passwordInfo = (TextView) findViewById(R.id.TextView_Password_Info);
                    String strPassword1 = p1.getText().toString();
                    String strPassword2 = p2.getText().toString();
                    if (strPassword1.equals(strPassword2)) {
                        Editor editor = mGameSettings.edit();
                        editor.putString(GAME_PREFERENCES_PASSWORD, strPassword1);
                        editor.commit();
                        passwordInfo.setText(R.string.settings_pwd_set);
                    } else {
                        Log.d(DEBUG_TAG, "Passwords do not match. Not saving. Keeping old password (if set).");
                    }
                    // We forcefully dismiss and remove the Dialog, so it
                    // cannot be used again
                    SettingsActivity.this.removeDialog(PASSWORD_DIALOG_ID);
                }
            });
            // Create the AlertDialog and return it
            AlertDialog passwordDialog = builder.create();
            return passwordDialog;
    }
    return null;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    super.onPrepareDialog(id, dialog);
    switch (id) {
        case DATE_DIALOG_ID:
            // Handle any DatePickerDialog initialization here
            DatePickerDialog dateDialog = (DatePickerDialog) dialog;
            int iDay, iMonth, iYear;
            // Check for date of birth preference
            if (mGameSettings.contains(GAME_PREFERENCES_DOB)) {
                // Retrieve Birth date setting from preferences
                long msBirthDate = mGameSettings.getLong(GAME_PREFERENCES_DOB, 0);
                Time dateOfBirth = new Time();
                dateOfBirth.set(msBirthDate);
                iDay = dateOfBirth.monthDay;
                iMonth = dateOfBirth.month;
                iYear = dateOfBirth.year;
            } else {
                Calendar cal = Calendar.getInstance();
                // Today's date fields
                iDay = cal.get(Calendar.DAY_OF_MONTH);
                iMonth = cal.get(Calendar.MONTH);
                iYear = cal.get(Calendar.YEAR);
            }
            // Set the date in the DatePicker to the date of birth OR to the
            // current date
            dateDialog.updateDate(iYear, iMonth, iDay);
            return;
        case PASSWORD_DIALOG_ID:
            // Handle any Password Dialog initialization here
            // Since we don't want to show old password dialogs, just set new
            // ones, we need not do anything here
            // Because we are not "reusing" password dialogs once they have
            // finished, but removing them from
            // the Activity Dialog pool explicitly with removeDialog() and
            // recreating them as needed.
            return;
    }
}

}

但是我收到错误,说“FirstNum / SecondNum”列不存在。

EDIT
到目前为止,我正在使用(作为一种解决方法)临时表,我正在添加一个字段,我存储比率,我正在使用该字段对表进行排序。

3 个答案:

答案 0 :(得分:0)

我不认为select方法足够聪明,可以在现场进行计算。另一种解决方法是将计算列添加到数据表中,并将其用作排序列

答案 1 :(得分:0)

尝试将每列放在括号内

Using DT_Tmp As DataTable = DT.Select("", "[FirstNum] / [SecondNum] desc").CopyToDataTable

答案 2 :(得分:0)

根据您查看的链接,您需要先添加caluculated列。

csortnum= New DataColumn
 With csortnum
     .DataType = System.Type.GetType("System.Decimal")
     .ColumnName = "sortcolumn"
     .Expression = "FirstNum/SecondNum"
 End With
DT.add(csortnum)
Using DT_Tmp As DataTable = DT.Select("", csortnum desc").CopyToDataTable