Create List in Linq

S

shapper

Hello,

I want to create a List(Of Tag) where Tag is an object with two
properties: ID and Name
I am creating this list from a CSV string that contains names of many
Tags.
So I create the List, giving to each Tag only its name (the ID remains
empty, as follows:

List<Tag> form = paper.Tags.Split(',').Select(p => new Tag { Name =
p.Trim() }).ToList();

What happens is that if the CSV is empty I still get one Tag in the
list with Name = "".

What am I doing wrong?

Thanks,
Miguel
 
M

Martin Honnen

shapper said:
Hello,

I want to create a List(Of Tag) where Tag is an object with two
properties: ID and Name
I am creating this list from a CSV string that contains names of many
Tags.
So I create the List, giving to each Tag only its name (the ID remains
empty, as follows:

List<Tag> form = paper.Tags.Split(',').Select(p => new Tag { Name =
p.Trim() }).ToList();

What happens is that if the CSV is empty I still get one Tag in the
list with Name = "".

What am I doing wrong?

If you don't want empty strings then you can filter them out:

List<Tag> form = paper.Tags.Split(',').Where(p => p != "").Select(p =>
new Tag { Name =
p.Trim() }).ToList();
 
P

Pierre T.

Hi!

You can use the StringSplitOptions.RemoveEmptyEntries as 2nd paramter to the
Split method.

Regards,

Pierre T.
 
S

shapper

Hi!

You can use the StringSplitOptions.RemoveEmptyEntries as 2nd paramter to the
Split method.

Regards,

Pierre T.

You mean:

List<Tag> form = paper.Tags.Split(new char[] {','},
StringSplitOptions.RemoveEmptyEntries).Select(t => new Tag { Name =
t.Trim() }).ToList();

It didn't work ... I still get one item ... Count = 1 of form list.

Am I doing something wrong?

Thanks,
Miguel
 
S

shapper

Hi!

You can use the StringSplitOptions.RemoveEmptyEntries as 2nd paramter to the
Split method.

Regards,

Pierre T.

My mistake ... both options worked! With StringSplitOptions and using
Where in Linq ... I suppose using StringSplitOptions is better in the
case ... I think ...

Thanks,
Miguel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

List conversion 2
Linq Query. Please, help. Going crazy ... 1
List to CSV 3
Linq. String 5
Linq. Join. 2
(Collection) 1
Linq.How to complete this query? 2
ToString and FromString 10

Top