Create List in Linq

  • Thread starter Thread starter shapper
  • Start date Start date
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
 
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();
 
Hi!

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

Regards,

Pierre T.
 
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
 
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
 
Back
Top