Anyname Donotcare
Anyname Donotcare

Reputation: 11423

How to get a specific field of list of objects in an array of strings

I have a list of persons like this :

foreach (GridViewRow r in gv_contactList.Rows)
                        {
                            Person p = new Person();
                            p.Id = int.Parse(gv_contactList.DataKeys[r.RowIndex].Value.ToString());
                            p.Name = r.Cells[1].Text.TrimEnd();
                            p.Mobile = r.Cells[2].Text.TrimEnd();
                            p.Email = r.Cells[3].Text.TrimEnd();
                            p.Pkind = 1;//ToDo
                            plst.Add(p);

                        }

How to get an array of mobile numbers in string[] in the same previous loop where the mobile number is not null or empty . instead of looping again through the list of persons to put the mobile numbers in the array.

Upvotes: 1

Views: 9613

Answers (4)

Wasp
Wasp

Reputation: 3425

Assuming plst is already existing:

var plst = ...

var persons = from GridViewRow r in gv_contactList.Rows
              select new Person {
                Id = int.Parse(gv_contactList.DataKeys[r.RowIndex].Value.ToString()),
                Name = r.Cells[1].Text.TrimEnd(),
                Mobile = r.Cells[2].Text.TrimEnd(),
                Email = r.Cells[3].Text.TrimEnd(),
                Pkind = 1,
              };

var mobiles = persons.Aggregate(new List<string>(), (acc, cur) => 
              {
                plst.Add(cur);

                if (!string.IsNullOrEmpty(cur.Mobile))
                    acc.Add(cur.Mobile);
                return acc;
              }).ToArray();

The enumeration happens just once.

Upvotes: 1

Habib
Habib

Reputation: 223332

Not really sure what you want. But if you want an array of string phone numbers from your Person List plst you can do:

string[] phoneArray = plist
                          .Where(r=>string.IsNullOrWhiteSpace(r.Mobile))
                          .Select(r=>r.Mobile.ToString())
                          .ToArray();

Upvotes: 2

Azodious
Azodious

Reputation: 13882

Declare an ArrayList before foreach:

ArrayList<String> mobNums = new ArrayList<String>();

within foreach add the mobile no. to it:

mobNums.Add(p.Mobile);

After foreach change it to Array:

String[] arr = mobNums.ToArray();

Upvotes: 1

Heinzi
Heinzi

Reputation: 172408

var mobiles = new List<string>();

foreach (GridViewRow r in gv_contactList.Rows) 
{ 
    ...
    p.Mobile = r.Cells[2].Text.TrimEnd(); 
    if (!String.IsNullOrEmpty(p.Mobile)) {
        mobiles.Add(p.Mobile);
    }
    ... 
} 

var mobilesArray = mobiles.ToArray();

Upvotes: 2

Related Questions