1

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.

4 Answers 4

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Can't convert Person[] to string[]
@just_name, my bad, forgot the Select Statement, you may remove .ToString if Mobile is already of type string
2
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();

Comments

1

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();

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.