[英]Working with arrays in c#
我的問題應該很簡單,我正在處理包含ID,名稱,貨幣數組的程序。 所以我分離了數組以使其更易於使用(搜索,添加等...),但是我覺得這樣做有更有效的方法,因為如果我僅搜索id並直接將數組放回去每次我找到一個匹配項。 有更好的方法嗎? 謝謝你的幫助。 這是我的一些代碼
// Variables for reading Accounts
static List<int> importedNumbers = new List<int>();
static List<string> people = new List<string>();
static List<decimal> Money = new List<decimal>();
static List<string> BorP = new List<string>();
// Variables for reading Transactions
static List<int> NumbersTrans = new List<int>();
static List<decimal> Amount = new List<decimal>();
static void Main(string[] args)
{
string path = @"path";
ReadTransactions(@"path");
ReadAccount(path);
Duplicates();
Charges(path);
Console.WriteLine("Type in ID to search ");
string id = Console.ReadLine();
int ID = int.Parse(id);
Search(importedNumbers, ID);
Console.ReadLine();
}
這是我程序的重要部分,有沒有更好的方法,所以我沒有那么多數組
首先-這些是列表,它們不是數組。 如果它們是數組,它們將是string[]
和int[]
。
但是,您絕對不應該擁有所有這些單獨的列表。 相反,找出相關類型是什么-從您的現有名稱中還不清楚,但是您可能想要類似以下內容:
Account
(具有ID, Account
持有人姓名和余額) Transaction
(可能包含源帳戶,目標帳戶和金額) 那么您可以擁有一個List<Account>
和一個List<Transaction>
。 基本上,每個邏輯項目集合都有一個集合。 您可能需要一個字典,以便您可以輕松地通過ID查找帳戶...但是我至少要從列表開始。
每當您發現兩個集合中始終具有相同項目數(例如x[0]
和y[0]
相關)時,您至少應考慮使用一個單個集合可能會更好新型。 有關更多示例,請參閱我關於此主題的博客文章 。
接下來,了解LINQ-在查詢數據時,它使工作變得更加輕松。
您應該聲明一個類來保存數據,並使用該類的對象列表。
class MyClass // (pick a more appropriate name, I don't know what kind of data you're handling)
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Money { get; set; }
public string BorP { get; set; }
}
...
List<MyClass> items = new List<MyClass>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.