Link to home
Start Free TrialLog in
Avatar of arjitbhandari
arjitbhandari

asked on

Groupby and add items to a list

Hello,

I am writing a C# program and in that I have a List<category> which I have defined. I am doing a group by on the items. My question is, how do I put these elements into the same List or even a different List? Do I need to use IEnumerator? If yes, then how do I do so?

Any help is greatly appreciated!

Thanks
Arjit
Avatar of jandromeda
jandromeda
Flag of Sri Lanka image

Your question is little bit unclear to me, but if you are trying to add items to certain places of the current list then you can use either List<T>).Insert(<index>,<T>) method or the List<T>.AddRange(<inderx>,IEnumerable<T>).
ASKER CERTIFIED SOLUTION
Avatar of jandromeda
jandromeda
Flag of Sri Lanka image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of arjitbhandari
arjitbhandari

ASKER

Thanks for your reply.

Basically, I have defined 2 List, ret and ret1, with reference to the following code snippet. When I add elements to ret, I do not have any problem, but when I try to add elements to ret1, which is of same type, I get the following error:

 "Cannot initialize type with a collection initializer because it does not implement 'System.Collections.IEnumerable'"

Note that the purpose of this code is to "group by" elements in List ret. Do you have any suggestions for this?

Thanks
Arjit
ret.Add(new Category()
                            {
                                GivenName = contact.GivenName,
                                //   Surname = contact.Surname,
                                //   PhoneNumber = (string)contact.PhoneNumbers[0].Value,
                                CompanyName = contact.CompanyName,
                                JobTitle = contact.JobTitle,
                                BAddress = contact.PhysicalAddresses[0].Street,
                                City = contact.PhysicalAddresses[0].City,
                                State = contact.PhysicalAddresses[0].State,
                                Zip = contact.PhysicalAddresses[0].PostalCode,
                                Country = contact.PhysicalAddresses[0].CountryOrRegion
                                
                            });
                        var temp = from p in ret
                                   group p by p.Country
                                   ;
 
                        foreach (var i in temp)
                            foreach (var temp2 in i)
                            {
                                ret1.Add(new Category() { temp2.GivenName });
                            }

Open in new window

I am also attaching the cs file for reference. Thanks in advance.

Arjit
collection.txt