2015-03-14 3 views
1

Я думаю, что я должен сделать, это разделить и извлекать данные, чтобы сделать следующее:Разбиение данных из массива и тянущие конкретные данные

Я создал класс, со следующей матрицей и методом getContactList. Мне нужно создать метод getFirstNames() и вернуть все первые имена из адресной книги в переменную firstNames в классе Test и отобразить их на консоли.

class ContactList 
{ 
    public String[] contactList = 
    { 
    "John, Smith, [email protected], (506) 555-1234", 
    "Frank, Sinatra, [email protected], (506) 696-1234", 
    "Joan, Rivers, [email protected], (506) 696-5678", 
    "Freddy, Mercury, [email protected], (506) 653-1234", 
    "Freddy, Kruger, [email protected], (506) 658-1234" 
    }; 

     public String[] getContactList() 
    { 

     return contactList; 
    } 


    public String getLastNames() 
    { 
     string lastnames = ""; 

     return lastnames; 
    } 


} 


class Program 
{ 
    static void Main(string[] args) 
    { 
     ContactList firstNames = new ContactList(); 
     Console.WriteLine(firstNames.getFirstNames()); 

     Console.WriteLine(); 
     Console.WriteLine("Press any key to exit."); 
     Console.ReadKey(); 

    } 
+0

Почему вы положить жестко закодированные данные в классе? –

ответ

0

Лучше дизайн это так:

class ContactList 
{ 
string firstName, lastName, eMail, ContactNo; 
//Properties (getters/setters for above attributes/fields 
} 

class ContactListHandler 
{ 

public List<string> GetFirstNames(string[] contactsText) 
{ 

List<string> stringList = new List<string>(); 

foreach (string s in contactsText) 

{ 
var x = contactsText.split(','); 
stringList.Add(x[0]); 
} 

return stringList; 
} 

//and other functions 
} 

Main() 
{ 
ContactListHandler cHandler = new ContactListHandler(); 
List<string> contactsString = cHandler.GetFirstNames(//your string variable containing the contacts); 

foreach(string s in contactsString) 
{ 
Console.WriteLine(s); 
} 
} 

Да, он имеет увеличенный код, но только один раз, теперь вы можете использовать его объектно-ориентированным способом для любой строки и т. Д.

+0

GREAT :) Спасибо – LizG

+0

@Talha Irfan, система голосования предназначена для того, чтобы подчеркнуть полезность ответов, а не для того, чтобы сбить кого-то на ваш вопрос собственной выгоды. –

+0

@ Урахара Pardon? –

1

Ваш не совсем лучший подход, но добиться того, что вы хотите ... (если вы хотите отделить имена от,)

public string getFirstNames(){ 
    StringBuilder sb=new StringBuilder(); 
    foreach(var x in contactList){ 
     var tmp=x.Split(','); 
     sb.Append(tmp[0]); 
     sb.Append(","); 
    } 
    return sb.ToString(); 
} 
+0

При попытке поместить «var» в мой код в Visual Studio 2013, это не позволяет мне. Является ли «var» фактическим ключевым словом в C#? Или он должен представлять тип данных? – LizG

+0

Спасибо, это помогает – LizG

+0

Когда вы используете var, вам также нужно назначить ему значение/ссылку, иначе компилятор не может вывести тип. Если ответ был полезен, не забудьте перечесть/отметить как ответ. –

0

Он работает, я проверил :) удачи с вашим развитием

using System.IO; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
class Program 
{ 

    static void Main() 
    { 
     // Just to hold data 
     string[] data = new String[]{"John, Smith, [email protected], (506) 555-1234","Frank, Sinatra, [email protected], (506) 696-1234","Joan, Rivers, [email protected], (506) 696-5678","Freddy, Mercury, [email protected], (506) 653-1234","Freddy, Kruger, [email protected], (506) 658-1234"}; 

     // Create new contact list object 
     ContactList contacts = new ContactList(data); 

     // Call our method 
     contacts.PrintLastNames(); 

    } 
} 


public class ContactList 
{ 
    // Declare properties 
    // google C# getter setter 
    private List<string> cList; 
    public List<string> CList{ 
     get{ return cList; } 
    } 

    // Constructor 
    public ContactList(string[] _contactList) 
    { 
     // When creating new instance, take array of contacts and put into list  
     this.cList = _contactList.ToList(); 
    } 

    // This will print out the names 
    public void PrintLastNames() 
    { 
     // Google lambda expression C# for more info on iteration 
     // With each string in cList, split by comas and use the first element 
     this.cList.ForEach(x => Console.WriteLine(x.Split(',')[0])); 

     // Use this for last names 
     //this.cList.ForEach(x => Console.WriteLine(x.Split(',')[1])); 
    } 

    // This will return names in list 
    public List<string> GetLastNames() 
    { 
     // Google List Collection Generic C# for more info 
     List<string> namesList = new List<string>(); 
     this.cList.ForEach(x => namesList.Add(x.Split(',')[0])); 

     return namesList; 
    } 

} 
+0

Большое спасибо за вашу помощь! :) – LizG

+0

Пожалуйста, отметьте, как было решено, и +1, чтобы сделать его полезным для других пользователей. –

+1

как? в первый раз здесь, я просто положил «Solved, +1» в комментарии? – LizG

Смежные вопросы