Deleting elements from array

ankit goel 766 Reputation points
2022-12-07T11:32:14.343+00:00

I am trying to delete a range of elements like first top 10 elements and the last element from an object array but i am getting the following error. Please suggest how to solve the problem. please note that there is a duplicity of data in my element's so using dictionary data type is not suitable for me
268153-query1.jpg

Also, please suggest how to add "₹" symbol in the end of the element.

Developer technologies C#
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2022-12-08T02:59:38.697+00:00

    @ankit goel , Welcome to Microsoft Q&A, you could try to convert object[,] to List<object[]> to remove some elements from list.

    Here is a code example you could refer to.

                   Console.OutputEncoding = System.Text.Encoding.Unicode;  
                    var valueArray = (object[,])range1.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);  
                    List<object[]> list = new List<object[]>();  
                    for (int i = 1; i <= valueArray.GetLength(0); i++)  
                    {  
                        list.Add(new object[] { valueArray[i, 1], valueArray[i, 2] + "₹" });  
                    }  
                    list.RemoveAt(list.Count - 1);  
                    list.RemoveRange(0, 10);  
                    foreach (var item in list)  
                    {  
                        Console.WriteLine(item[0] + "----" + item[1]);  
                    }  
                    wkb.Close();  
                    excel.Quit();  
    

    I removed first top 10 elements and the last element.

    My excel and tested result:

    268472-image.png

    Best Regards,
    Jack


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-12-07T16:22:06.703+00:00

    C# arrays do not have a slice(). You use the copy(). This requires allocating a new array the size you want, then copy from the old.

    var a1 = new int[] {1,2,3,4,5};    
        
    // remove first two elements (no bounds checking)    
    var a2 = new int[a1.Length -2];    
    Array.Copy(a1, 2, a2, 0, a2.Length);    
    a1 = a2;    
        
    

    you could also write an slice array extension:

    public static class ArrayExtensions  
    {  
    	public static T[] Slice<T> (this T[] a, int start, int end)   
    	{  
    		var c = new T[end - start + 1];  
    		Array.Copy(a, start, c, 0, c.Length);  
    		return c;  
    	}  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.