DataTables по сравнению с IEnumerable <T>

Несколько ошибок

if (choice = 'M') // if its monthly 
    mterm = 12; // there are 12 months within a year

Первое, что следует сказать

if (choice == 'M') // if its monthly 
    mterm = 12; // there are 12 months within a year

В C ++ мы используем == для проверки на равенство и = для присвоения переменной.

Еще более серьезно подумайте об этом

if (choice == 'M') // if its monthly 
    mterm = 12; // there are 12 months within a year
cout << "How many years will this loan be for?" << endl;
cin >> years; // I need this information for getting the exact
month = mterm * years;

Теперь предположим, что choice - это не 'M'. Как вы думаете, каким будет значение mterm?

Ответ таков: что это не определено. Тем не менее, вы используете переменную в формуле двумя строками вниз. Плохо использовать переменные с неопределенными значениями.

Мне кажется, что вам нужно реструктурировать свой код, чтобы включить больше операторов в оператор if

if (choice == 'M')
{
    mterm = 12; // there are 12 months within a year
    cout << "How many years will this loan be for?" << endl;
    cin >> years; // I need this information for getting the exact
    month = mterm * years;
    sqrdMonth = sqrt(month); // I need to square root the months for the periodic payment formula
    monthlypayment = (prinicple * rate) / (rate); sqrdMonth; // this is where my problem is 
                                            //  ^^^^ why is it asking me to close my equation with a ';'
    cout << "Your monthly loan payment is: ";
    cout << monthlypayment;
}

Наконец, это

monthlypayment = (prinicple * rate) / (rate); sqrdMonth;

У меня нет Идея, почему у вас есть две точки с запятой. Не имеет смысла для меня, но я не уверен, что формула должна быть. Там нет упоминания о квадратных корнях в формуле в вашем вопросе, поэтому я не уверен, почему вы включили один здесь.

21
задан CRice 29 December 2017 в 02:58
поделиться

4 ответа

DataTables are definitely much heavier than Lists, both in memory requirements, and in processor time spent creating them / filling them up.
Using a DataReader is considerable faster (although more verbose) than using DataTables (I'm assuming you're using a DataAdapter to fill them).

That said... Unless this is in some place where it really matters, you're probably fine either way, and both methods will be fast enough, so just go with whatever is more comfortable in each case. (Sometimes you want to fill them up with little code, sometimes you want to read them with little code)

I myself tend to only use DataTables when I'm binding to a GridView, or when I need more than one resultset active at the same time.

21
ответ дан 29 November 2019 в 20:21
поделиться

Мне также нравится тот факт, что с помощью IEnumerable<T> вы можете улучшить базовый тип коллекции с помощью методов и свойств, что делает реализацию намного более элегантной, а код - более понятным. Например, свойство FullName. Вы также можете добавить методы расширения в класс, если он находится вне вашего контроля.

public class SomeUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get { return String.Format("{0} {1}", FirstName, LastName); } }
}
8
ответ дан 29 November 2019 в 20:21
поделиться

Еще одно преимущество использования классов System.Collections состоит в том, что вы получаете лучшие параметры сортировки и поиска. Я не знаю разумного способа изменить способ сортировки или поиска DataTable; с классами коллекций у вас просто есть класс, реализующий IComparable или IEquatable, и вы можете полностью настроить работу List.Sort и List.Contains.

Также со списками вам не нужно беспокоиться о DBNull, который меня сбил с толку более одного раза, потому что я ожидал null и получил DBNull.

10
ответ дан 29 November 2019 в 20:21
поделиться

Using DataTables directly means tying yourself to the underlying data source and how it is laid out. This is not good from a maintainability point of view. If all your view needs is a list of some objects, that's all you should be giving it.

6
ответ дан 29 November 2019 в 20:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: