简体   繁体   中英

Comma separated values to List

I have a List like,

Class Traking {
public sting TrackID {get;set}
public sting AlertID {get;set} // Comma separated Values
}

            TrackID    AlertID
            1001       101,102,103
            1002       201,202,203
            1003       301,302,303

AlertID having comma seperated values, Using Linq convet to Like this

           TrackID   AlertID
           1001       101
           1001       102
           1001       103
           1002       201
           1002       202
           1002       203
           1003       301
           1003       302
           1003       303

Ex:
Turning a Comma Separated string into individual rows - This done from SQL, the same way need to do in LinQ

I hope understand my problem

If your object looks like this:

class Traking 
{
    public string TrackID {get;set;}
    public string AlertID {get;set;} // Comma separated Values
}

And your list looks like this:

var ls=new List<Traking>
    {
        new Traking(){TrackID = "1001",AlertID = "101,102,103"},
        new Traking(){TrackID = "1002",AlertID = "201,202,203"},
        new Traking(){TrackID = "1003",AlertID = "301,302,303"},
    };

Then you can do this:

var result= ls.SelectMany (l => l.AlertID.Split(',').Select (s =>new Traking()
    {
        TrackID=l.TrackID,
        AlertID=s
    } )).ToList()

To get this output:

TrackID    AlertID
1001       101 
1001       102 
1001       103 
1002       201 
1002       202 
1002       203 
1003       301 
1003       302 
1003       303 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM