none
Split string, add a new object list RRS feed

  • Question

  • Hello everybody,
    Is there a way to automatically increment the index from the received string, separated by a comma.
    How I can delete space, with Trim(), another way?
    My code works well, but I think there is a better way.
    responseData	"234523535,5r3253245342,3253245214,3215325,321532523"	
    
    ListSerials.AddRange(from item in responseData.Split(',') select new Serial(item));
    
    
    //Product.ListSerials.AddRange(from item in unusedSerialForPanel.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) select new Serial(item));
    
    int i = 0;
    foreach (var item in Product.ListSerials)
    {
    	item.Index = ++i;
    	item.SerialToWrite = item.SerialToWrite.Trim();
    	Trace.WriteLine($"Index={item.Index}, serial={item.SerialToWrite}");
    }
    			
    Index=1, serial=234523535
    Index=2, serial=5r3253245342
    Index=3, serial=3253245214
    Index=4, serial=3215325
    Index=5, serial=321532523
    
    
    public class Serial
    {
    	public int Index { get; set; }
    	public string SerialToWrite { get; set; }
    
    	public Serial()
    	{
    		Index = -1;
    		SerialToWrite = "NotDefine";
    	}
    
    	public Serial(string fromTelegram)
    	{
    		Index = -1;
    		SerialToWrite = fromTelegram;
    	}
    }

    With best regards Markus
    Tuesday, June 5, 2018 4:52 PM

Answers

All replies

  • I'm not sure there's anything wrong with this.  The other alternative is do skip the AddRange and do everything inside of one loop:

        foreach( var item in responseData.Split('.') )
        {
            ListSerials.Add( new Serial( ListSerials.Count(), item.Trim() );
        }

    You'd have to change class Serial to specify the index in the constructor.


    Tim Roberts, Driver MVP Providenza & Boekelheide, Inc.

    Tuesday, June 5, 2018 8:25 PM
  • Try this too:

    ListSerials.AddRange( responseData.Split( ',' ).Select( ( s, i ) => new Serial { Index = i + 1, SerialToWrite = s.Trim() } ) );


    Tuesday, June 5, 2018 9:17 PM
  • perfect, thanks.
    Wednesday, June 6, 2018 4:53 PM