KeyValue对C#

时间:2018-04-30 18:14:22

标签: c# keyvaluepair

我想知道如何使用C#中的KeyValuePairs列表。我会使用词典,但他们不允许重复值。

此外,我也无法弄清楚如何编写语法的查找。

我见过其他解决方案,但我真的很困惑如何使用

当然,我能找到的唯一例子是for for循环,我希望它有点清洁。

List<KeyValuePair<char, int>> data = new List<KeyValuePair<char, int>>();

我想在添加元素之前做一些检查。 例如:我有一个字符数组,我想在将它添加到我的列表之前检查。任何人都可以告诉我如何检查。

char[] inputArray = input.ToCharArray();
for(int i = 0; i < inputArray.Length ; i++)
{
    if(!data.Values.Contains(inputArray[i]))
    {
        data.Add(new KeyValuePair<char,int>(inputArray[i], 1));
    }
}

上述代码不起作用。有人可以请一点帮助语法。

我没有在网上找到任何具体的例子。 任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

我不得不说,你的问题相当令人困惑。如果密钥尚未存在,我您是否尝试将值添加到// // ServicesTableViewController.swift // Contact Australis // // Created by Raghav Khanna on 22/4/18. // Copyright © 2018 Australis. All rights reserved. // import UIKit class ServiceViewCell: UITableViewCell { @IBOutlet weak var IMage: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code IMage.frame = CGRect(x: 0, y: 0, width: 100, height: 200) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } class ServiceViewCellList: UITableViewCell { @IBOutlet weak var somethin_label: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code let color = UIColor(red: 0/255, green: 105/255, blue: 191/255, alpha: 1.0).cgColor let back_colour = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0).cgColor let back_colour_ui = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0) let radius: CGFloat = 5 let border_width:CGFloat = 1.5 somethin_label.layer.borderColor = color somethin_label.layer.borderWidth = border_width somethin_label.layer.cornerRadius = radius somethin_label.backgroundColor = back_colour_ui } var items_maintenance = ["Painting","All Lighting & Globe Replacemt", "Carpet & Hard Floor Replacement","Electrical Work & Maintenance","Plumbing Work & Maintenance","Test & Tag Completion","Office Furniture Removal", "Hard Waste Removal", "Window Frosting", "All Other Handy Man & Maintenance Tasks"] override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } class ServiceViewCellCleaning: UITableViewCell { @IBOutlet weak var Title: UIImageView! override func awakeFromNib() { super.awakeFromNib() Title.frame = CGRect(x: 0, y: 0, width: 100, height: 200) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } class ServiceViewCellCleaningList: UITableViewCell { @IBOutlet weak var other_label: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code let color = UIColor(red: 0/255, green: 105/255, blue: 191/255, alpha: 1.0).cgColor let back_colour = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0).cgColor let back_colour_ui = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0) let radius: CGFloat = 5 let border_width:CGFloat = 1.5 other_label.layer.borderColor = color other_label.layer.borderWidth = border_width other_label.layer.cornerRadius = radius other_label.backgroundColor = back_colour_ui } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } class ServicesTableViewController: UITableViewController { let basicCellIdentifier = "BasicCell" var items_maintenance = ["Painting","All Lighting & Globe Replacement", "Carpet & Hard Floor Replacement","Electrical Work & Maintenance","Plumbing Work & Maintenance","Test & Tag Completion","Office Furniture Removal", "Hard Waste Removal", "Window Frosting", "All Other Handy Man & Maintenance Tasks"] var items_cleaning = ["All Genral Comercial Cleaning","Office Cleaning", "Initial Clean","Spring Clean","Steam Carpet Cleaning","Window Washing","High Pressure Washing", "Waste Removal", "Strip & Seal Hard Floors", "Scrubbing & Buffing Hard Floors"] let cellSpacingHeight: CGFloat = 5 @IBOutlet var table: UITableView! func configureTableView() { //tableView.rowHeight = UITableViewAutomaticDimension //tableView.estimatedRowHeight = 1000.0 //let rect = CGRect(origin: .zero, size: CGSize(width: 400, height: 400)) //self.tableView = UITableView(frame: rect, style: UITableViewStyle.plain) table.register(ServiceViewCell.self, forCellReuseIdentifier: "maintenance") table.register(ServiceViewCellList.self, forCellReuseIdentifier: "customcell") table.register(ServiceViewCellCleaning.self, forCellReuseIdentifier: "cleaning") table.register(ServiceViewCellCleaningList.self, forCellReuseIdentifier: "cleaning_customcell") } /*func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return }*/ override func viewDidLoad() { super.viewDidLoad() self.configureTableView() table.reloadData() table.delegate = self table.dataSource = self // Uncomment the following line to preserve selection between presentations self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 4 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else if section == 1 { return items_maintenance.count } else if section == 2 { return 1 } else { return items_cleaning.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let maintenance_title = table.dequeueReusableCell(withIdentifier: "maintenance", for: indexPath) as! ServiceViewCell let maintenance_list = table.dequeueReusableCell(withIdentifier: "customcell", for: indexPath) as! ServiceViewCellList let cleaning_title = table.dequeueReusableCell(withIdentifier: "cleaning", for: indexPath) as! ServiceViewCellCleaning let cleaning_list = table.dequeueReusableCell(withIdentifier: "cleaning_customcell", for: indexPath) as! ServiceViewCellCleaningList maintenance_list.somethin_label?.text = self.items_maintenance[indexPath.row] maintenance_list.somethin_label?.adjustsFontSizeToFitWidth = false maintenance_list.somethin_label?.font = UIFont.systemFont(ofSize: 10.0) cleaning_list.other_label?.text = "test" cleaning_list.other_label?.adjustsFontSizeToFitWidth = false cleaning_list.other_label?.font = UIFont.systemFont(ofSize: 10.0) cleaning_title.Title?.image = UIImage(named: "cleaning.png") maintenance_title.IMage?.image = UIImage(named: "maintenance.png") if indexPath.section == 0 { return maintenance_title } else if indexPath.section == 1 { return maintenance_list } else if indexPath.section == 2 { return cleaning_title } else { return cleaning_list } return cleaning_list } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ //Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return false } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } 列表中?这似乎与你所说的不使用KeyValuePair的内容相吻合,但无论如何你都去了:

Dictionary

如果您只想从inputArray获取唯一值,您也可以这样做:

List<KeyValuePair<char, int>> data = new List<KeyValuePair<char, int>>();

char[] inputArray = "my string".ToCharArray();
foreach (var t in inputArray)
{
    if (!data.Any(x => x.Key == t))
    {
        data.Add(new KeyValuePair<char, int>(t, 1));
    }
}

最后,如果你想获得字符串中每个不同字符的计数,你可以使用:

var myVals = inputArray.Distinct();

答案 1 :(得分:0)

根据你的评论真的听起来像你想要一个字典。

考虑一下你的逻辑,你在添加到列表之前已经检查了重复项吗?这意味着您的列表永远不会重复。字典会阻止您重复键,而不是重复值。所以你的逻辑很容易变成:

var dictionary = new Dictionary<char, int>();
foreach(char c in input)
{
    //faster than Any()
    if(!dictionary.ContainsKey(c))
    {
        dictionary.Add(c, 1);
    }
}