How to get value from list string? - c#

The return result of string list is :
var result= "1,red,2,blue,3,green,4,orange";
I want to use a loop and get result like 1,2,3,4 and red,blue,green,orange
My code is as below.
I got the error in split.
Object does not support for split().
I am using jquery 1.10.1 .
$.ajax({
type: "GET",
url: "/_vti_bin/userService/myservice.svc/GetUserListForMentionSign?query" + query,
async: false,
dataType: "JSON",
cache: false,
processdata: true,
success: function (result) {
data = result;
//arrary
var resultArray = data.Split(',');
var id = new Array(), name = new Array();
$.each(resultArray, function (index, value) {
if (isNaN(value)) {
name.push(value);
alert(name.push(value));
}
else {
id.push(value);
}
});
Here is the web service for c#.
public List<string> GetUserListForMentionSign(string username)
{
List<User> UserList = new List<User>();
List<string> returnvalue=new List<string>();
try
{
string returnstring = string.Empty;
DataTable dt = null;
dt = Library.Helper.FindUser(username, 200);
foreach (DataRow dr in dt.Rows)
{
if (dr["Title"].ToString() != "Person.aspx") // those user without the name
{
User user = new User();
user.id = dr["ID"].ToString();
user.name = dr["Name"].ToString();
UserList.Add(spuser);
}
}
}
catch (Exception ex)
{
}
return UserList.Select(a=>new[]{ a.name.ToString(),a.id.ToString()}).SelectMany(a=>a).ToList();
}

You can use jQuery map function to create 2 different arrays containing even and odd indexed values and manipulate it
var result = "1,red,2,blue,3,green,4,orange";
var arr=result.split(',');
var odd = jQuery.map( arr, function(n,i){
return i%2 ? n : null;
});
var even = jQuery.map( arr, function(n,i){
return i%2 ? null : n;
});

Try this : Use .split() to convert string into array and then iterate array. Inside loop check if value is number of not using isNaN() and push values to respective array.
var result= "1,red,2,blue,3,green,4,orange";
var resultArray = result.split(",");
var numberArray = new Array(), colorArray = new Array();
$.each(resultArray , function( index, value ) {
if(isNaN(value))
colorArray.push(value);
else
numberArray.push(value);
});
alert(colorArray.toString());
alert(numberArray.toString());

try
var result = "1,red,2,blue,3,green,4,orange";
var splitValue = result.split(",");
var num = [];
var str = [];
for (var i in splitValue) {
if (i % 2 === 0) {
num.push(splitValue[i]);
} else {
str.push(splitValue[i]);
}
}
console.log(num);
console.log(str);

In C language I have implemented like this.
Logic: input is parsed to split num&strings and stored to different array. At the end result array is printed.
int main()
{
char *str, result []= "1,red,2,blue,3,green,4,orange";
char *p, *p1;
char num[10], i=0;
char name[10][15], j=0,k;
str =result;
while (1)
{
p= strchr (str, ',');
if(!p1)
break;
num [i]=atoi (p-1) ;
i++;
p1= strchr (p+1, ',');
if(!p1){
strcpy ( name[j], p+1);
j++;
break;
}
p1[0]='\0';
strcpy ( name[j], p+1);
j++;
str=p1+1;
}
for (k=0; k<i; ++k){
printf ( "%d ", num[k]);
}
printf ("\n");
for (k=0; k<j; ++k){
printf ( "%s ", name[k]);
}
printf ("\n");
}

var result= "1,red,2,blue,3,green,4,orange";
string[] arr = result.Split(',');
int[] num;
string[] text;
foreach(var i in arr)
{
int cont;
if (int.TryParse(i, out cont) == false)
text[] = i;
else
num[] = cont;
}
or loop manually
for(int i = 0; i < arr.lenght; i++)
{
int cont;
if (int.TryParse(arr[i], out cont) == false)
text[i] = i;
else
num[i] = cont;
}
note : splitting from server side for C#.

Related

Group multiple rows containing index and create list of custom objects for each index

I have got a List of strings (read from a file) in this order and format and need to convert into List of class.
1.0.1.0.1, Type: DateTime, Value: 06/03/2013 11:06:10
1.0.1.0.2, Type: DateTime, Value: 06/03/2014 11:06:10
1.0.1.0.3, Type: DateTime, Value: 06/03/2015 11:06:10
1.0.1.0.4, Type: DateTime, Value: 06/03/2016 11:06:10
1.0.1.0.5, Type: DateTime, Value: 06/03/2017 11:06:10
1.0.1.1.1, Type: Integer, Value: 1
1.0.1.1.2, Type: Integer, Value: 2
1.0.1.1.3, Type: Integer, Value: 3
1.0.0.1.4, Type: Integer, Value: 4
1.0.1.1.5, Type: Integer, Value: 5
1.0.1.2.1, Type: String, Value: Hello
1.0.1.2.2, Type: String, Value: Hello1
1.0.1.2.3, Type: String, Value: Hello2
1.0.1.2.4, Type: String, Value: Hello3
1.0.1.2.5, Type: String, Value: Hello4
Here is my class
public class MyData
{
public DateTime DateTime {get;set;}
public int Index {get;set;}
public string Value {get;set;}
}
Now What I wanted is to convert it into a list of C# class
Something like this...
List<MyData> myDataList = new List<MyData>();
MyData data1 = new MyData();
data1.DateTime = "06/03/2013 11:06:10";
data1.Index = 1;
data1.Value = "Hello";
myDataList.Add(data1);
MyData data2 = new MyData();
data2.DateTime = "06/03/2014 11:06:10";
data2.Index = 2;
data2.Value = "Hello1";
myDataList.Add(data2);
and so on..
This is what I have tried so far.
List<List<string>> allLists = lines
.Select(str => new { str, token = str.Split('.') })
.Where(x => x.token.Length >= 4)
.GroupBy(x => string.Concat(x.token.Take(4)))
.Select(g => g.Select(x => x.str).ToList())
.ToList();
Do I really need to iterate or can I modify My LINQ to get me desired output ?
Here is my iteration.
foreach (var list in allLists)
{
MyData data = new MyData();
var splittedstring = list[0].Split(',').ToList();
if (splittedstring.Count == 3)
{
var valueData = splittedstring [2];
var indexof = valueData.IndexOf(':');
var value = valueData.Substring(indexof + 1);
// But Over here, how will get DateTime and Index ?
data.Value = value;
}
}
First, fix your GroupBy: string.Concat(x.token.Take(4)) may create uncertainties when dot-separated numbers are ambiguous. For example, 1.23.4.5 and 12.3.4.5 would both produce "12345" string. Use string.Join with some non-numeric separator instead:
.GroupBy(x => string.Join("|", x.token.Take(4)))
Now for the main part of your question an easy fix would be to add a static method that parses the list of three strings, and use it in your LINQ query:
List<MyData> dataList = lines
.Select(str => new { str, token = str.Split('.') })
.Where(x => x.token.Length >= 4)
.GroupBy(x => string.Concat(x.token.Take(4)))
.Select(g => g.Select(x => x.str).ToList())
.Where(list => list.Count == 3)
.Select(MyDataFromList)
.ToList();
...
private static MyData MyDataFromList(List<string> parts) {
if (parts.Count != 3) {
throw new ArgumentException(nameof(parts));
}
var byType = parts
.Select(ToTypeAndValue)
.ToDictionary(t => t.Item1, t => t.Item2)
return new MyData {
DateTime = DateTime.Parse(byType["DateTime"])
, Index = int.Parse(byType["Integer"])
, Value = byType["String"]
};
}
private static Tuple<string,string> ToTypeAndValue(string s) {
var tokens = s.Split(',');
if (tokens.Length != 3) return null;
var typeParts = tokens[1].Split(':');
if (typeParts.Length != 2 || typeParts[0] != "Type") return null;
var valueParts = tokens[2].Split(':');
if (valueParts.Length != 2 || valueParts[0] != "Value") return null;
return Tuple.Create(typeParts[1].Trim(), typeParts[2].Trim());
}
Note that the above code makes an assumption that the three types are unique (hence the use of Dictionary<string,string>). This is required, because the structure of your data provides no other way to tie the values to fields of MyData.
You can do this using regular expressions. It would look like:
public List<MyData> GetData(string str){
var regexDate = new Regex(#"\d\.\d\.\d\.\d\.(?<id>\d).*DateTime.*Value:\s*(?<val>.*)");
var regexInteger = new Regex(#"\d\.\d\.\d\.\d\.(?<id>\d).*Integer.*Value:\s*(?<val>.*)");
var regexString = new Regex(#"\d\.\d\.\d\.\d\.(?<id>\d).*String.*Value:\s*(?<val>.*)");
var dict = new Dictionary<int, MyData>();
foreach (Match myMatch in regexDate.Matches(str))
{
if (!myMatch.Success) continue;
var index = int.Parse(myMatch.Groups["id"].Value);
dict[index] = new MyData()
{
Index = index,
DateTime = DateTime.ParseExact(myMatch.Groups["val"].Value, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
};
}
foreach (Match myMatch in regexInteger.Matches(str))
{
if (!myMatch.Success) continue;
var index = int.Parse(myMatch.Groups["id"].Value);
dict[index].Index = Int32.Parse(myMatch.Groups["val"].Value);
}
foreach (Match myMatch in regexString.Matches(str))
{
if (!myMatch.Success) continue;
var index = int.Parse(myMatch.Groups["id"].Value);
dict[index].Value = myMatch.Groups["val"].Value;
}
return dict.Values
}
Here is my solution to your problem. I have already tested it, you can test it to here: Raw To Custom List
string text = rawData;
//Raw Data Is the exact data you read from textfile without modifications.
List<MyData> myDataList = new List<MyData>();
string[] eElco = text.Split( new[] { Environment.NewLine }, StringSplitOptions.None );
var tmem = eElco.Count();
var eachP = tmem / 3;
List<string> unDefVal = new List<string>();
foreach (string rw in eElco)
{
String onlyVal = rw.Split(new[] { "Value: " } , StringSplitOptions.None)[1];
unDefVal.Add(onlyVal);
}
for (int i = 0; i < eachP; i++)
{
int ind = Int32.Parse(unDefVal[i + eachP]);
DateTime oDate = DateTime.ParseExact(unDefVal[i], "dd/MM/yyyy hh:mm:ss",System.Globalization.CultureInfo.InvariantCulture);
MyData data1 = new MyData();
data1.DateTime = oDate;
data1.Index = ind;
data1.Value = unDefVal[i + eachP + eachP];
myDataList.Add(data1);
Console.WriteLine("Val1 = {0}, Val2 = {1}, Val3 = {2}",
myDataList[i].Index,
myDataList[i].DateTime,
myDataList[i].Value);
}
Here is my solution, using Regex. It could be improved by providing a conditional regex match based on the matched type named group(string), but I think the concept is clearer this way, and the regex easier to work with. As it stands, the date format is not validated to be as OP wrote them, they are assumed to be as OP wrote them.
This solution is tolerant to some extra spaces and parameters containing commas, but intolerant to inexact matches, i.e. extra fields added or removed in the rows in the future, etc.
The idea is to first parse the rows to a more "friendly" format, and then group the friendly format by index and return the MyData rows by iterating each group (by index).
Regex r = new Regex(#"^(?<fieldName>(\d\.)+(?<index>\d*)), *Type: *(?<dataType>.*), *Value: (?<dataValue>.*)$");
public class MyData
{
public DateTime DateTime { get; set; }
public int Index { get; set; }
public string Value { get; set; }
}
class LogRow
{
public int Index { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
//In a parser I would rather not be too defensive, I let exceptions bubble up
IEnumerable<LogRow> ParseRows(IEnumerable<string> lines)
{
foreach (var line in lines)
{
var match = r.Matches(line).AsQueryable().Cast<Match>().Single();
yield return new LogRow()
{
Index = int.Parse(match.Groups["index"].Value),
Type = match.Groups["dataType"].Value,
Value = match.Groups["dataValue"].Value
};
}
}
IEnumerable<MyData> RowsToData(IEnumerable<LogRow> rows)
{
var byIndex = rows.GroupBy(b => b.Index).OrderBy(b=> b.Key);
//assume that rows exist for all MyData fields for a given index
foreach (var group in byIndex)
{
var rawRow = group.ToDictionary(g => g.Type, g => g);
var date = DateTime.ParseExact(rawRow["DateTime"].Value, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
yield return new MyData() { Index = group.Key, DateTime = date, Value = rawRow["String"].Value };
}
}
Usage:
var myDataList = RowsToData(ParseRows(File.ReadAllLines("input.txt"))).ToList();
I'd just go for the manual approach... and since that list of integers at the start contains indices for the objects and for the properties, it'd only be logical to use these instead of the type strings.
Using a Dictionary, you can use that object-index to make a new object at the moment you find any of its properties, and store it using that index. And whenever you encounter another properties for the same index, you retrieve the object and fill in that property on it.
public static List<MyData> getObj(String[] lines)
{
Dictionary<Int32, MyData> myDataDict = new Dictionary<Int32, MyData>();
const String valueStart = "Value: ";
foreach (String line in lines)
{
String[] split = line.Split(',');
// Too many fail cases; I just ignore any line that stops matching at any point.
if (split.Length < 3)
continue;
String[] numData = split[0].Trim().Split('.');
if (numData.Length < 5)
continue;
// Using the 4th number as property identifier. Could also use the
// type string, but switch/case on a numeric value is more elegant.
Int32 prop;
if (!Int32.TryParse(numData[3], out prop))
continue;
// Object index, used to reference the objects in the Dictionary.
Int32 index;
if (!Int32.TryParse(numData[4], out index))
continue;
String typeDef = split[1].Trim();
String val = split[2].TrimStart();
if (!val.StartsWith(valueStart))
continue;
val = val.Substring(valueStart.Length);
MyData data;
if (myDataDict.ContainsKey(index))
data = myDataDict[index];
else
{
data = new MyData();
myDataDict.Add(index, data);
}
switch (prop)
{
case 0:
if (!"Type: DateTime".Equals(typeDef))
continue;
DateTime dateVal;
// Don't know if this date format is correct; adapt as needed.
if (!DateTime.TryParseExact(val, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateVal))
continue;
data.DateTime = dateVal;
break;
case 1:
if (!"Type: Integer".Equals(typeDef))
continue;
Int32 numVal;
if (!Int32.TryParse(val, out numVal))
continue;
data.Index = numVal;
break;
case 2:
if (!"Type: String".Equals(typeDef)) continue;
data.Value = val;
break;
}
}
return new List<MyData>(myDataDict.Values);
}

How to split a item in array to two item with conditional?

I have an example above.
Have array like:
array[0] = TODO 06:15PMJoin Michael
array[1] = WakeUp
array[2] = Going to schools
I want it become like:
array[0] = TODO 06:15PM
array[1] = Join Michael
array[2] = WakeUp
array[3] = Going to schools
In this example, I split item have content TODO 06:15PMJoin Michael to new two item.
Have two separate questions here:
How to create a role for creating a new item in an array?
I tried with my code:
var splitList = words.SelectMany(x => x.Contains("AM") || x.Contains("PM"))
But I don't know how to split from text AM or PM to the new item in arrays.
You can try finding AM/PM and get substrings:
String[] array = new String[] {
"TODO 06:15PMJoin Michael",
"WakeUp",
"Going to schools"
};
var result = array
.SelectMany(line => {
int p = line.IndexOf("AM");
if (p >= 0)
return new String[] {
line.Substring(0, p + "AM".Length),
line.Substring(p + "AM".Length) };
p = line.IndexOf("PM");
if (p >= 0)
return new String[] {
line.Substring(0, p + "PM".Length),
line.Substring(p + "PM".Length) };
return new String[] { line };
}
);
//.ToArray(); // if you want to have array representation
// Test
Console.Write(String.Join(Environment.NewLine, result));
You can also try this:
string[] array = new string[] {"TODO 06:15PMJoin Michael",
"WakeUp",
"Going to schools"};
string[] SplitArray(string[] array)
{
List<string> returnArray = new List<string>();
foreach (string item in array)
{
int index = GetIndex(item);
if (index >= 0)
{
string s1 = item.Substring(0, index + 2);
string s2 = item.Substring(index + 2);
returnArray.Add(s1);
returnArray.Add(s2);
}
else
{
returnArray.Add(item);
}
}
return returnArray.ToArray();
}
int GetIndex(string s)
{
int index = GetIndexOf(s, "AM");
if (index == -1)
{
index = GetIndexOf(s, "PM");
}
return index;
}
int GetIndexOf(string s, string delim)
{
int index = -1;
int tempIndex = 0;
do
{
tempIndex = s.IndexOf(delim, tempIndex);
if (tempIndex > 0)
{
if (char.IsDigit(s[tempIndex-1]))
{
index = tempIndex;
break;
}
}
}
while(tempIndex >= 0);
return index;
}

HOW TO MAKE create var array dynamic in C#

In my controller I'm using following code to return the 2 lists to ajax request:
public JsonResult getdata(int seat_plane_id)
{
int lid;
layoutsController L = new layoutsController();
JsonResult result = L.getlayouts(seat_plane_id);
List<layouts> L1 = (List<layouts>)result.Data;
List<SeatPlans>[] allUser = new List<SeatPlans>[2];
for(int i=0; i<L1.Count; i++)
{
String lid1 = L1[i].ticket_no_start;
lid = Int32.Parse(lid1);
allUser[i]= new List<SeatPlans>();
allUser[i]= db.SEATPLAN.Where(d => d.layout_id == lid).ToList();
}
var v = new { allUser0 = allUser[0], allUser1 = allUser[1] ,allUser2= allUser[2] };
return Json(v, JsonRequestBehavior.AllowGet);
}
I'm catching the returned value in ajax request as:
success: function (v) {
loadData(v.allUser0);
loadData(v.allUser0);
}
But my problem is: I will have a dynamic size of allUser (size is L1.Count). And so I will get L1.Count no of lists. So I need to create var v={ } dynamically. How to do this? If you have any other solution, it is acceptable.
Simply make v a dictionary. The serializer will generate identical JSON for you as you would have had with the dynamic object.
var v = new Dictionary<string, SeatPlans>();
int id = 0;
foreach (SeatPlans sp in allUser)
{
v.Add($"allUser{id}", sp);
id++;
}
return Json(v, JsonRequestBehavior.AllowGet);

Array.Sort for strings with numbers [duplicate]

This question already has answers here:
Natural Sort Order in C#
(18 answers)
Closed 8 years ago.
I have sample codes below:
List<string> test = new List<string>();
test.Add("Hello2");
test.Add("Hello1");
test.Add("Welcome2");
test.Add("World");
test.Add("Hello11");
test.Add("Hello10");
test.Add("Welcome0");
test.Add("World3");
test.Add("Hello100");
test.Add("Hello20");
test.Add("Hello3");
test.Sort();
But what happen is, the test.Sort will sort the array to:
"Hello1",
"Hello10",
"Hello100",
"Hello11",
"Hello2",
"Hello20",
"Hello3",
"Welcome0",
"Welcome2",
"World",
"World3"
Is there any way to sort them so that the string will have the correct number order as well?
(If there is no number at the end of the string, that string will always go first - after the alphabetical order)
Expected output:
"Hello1",
"Hello2",
"Hello3",
"Hello10",
"Hello11",
"Hello20",
"Hello100",
"Welcome0",
"Welcome2",
"World",
"World3"
Here is a one possible way using LINQ:
var orderedList = test
.OrderBy(x => new string(x.Where(char.IsLetter).ToArray()))
.ThenBy(x =>
{
int number;
if (int.TryParse(new string(x.Where(char.IsDigit).ToArray()), out number))
return number;
return -1;
}).ToList();
Create an IComparer<string> implementation. The advantage of doing it this way over the LINQ suggestions is you now have a class that can be passed to anything that needs to sort in this fashion rather that recreating that linq query in other locations.
This is specific to your calling a sort from a LIST. If you want to call it as Array.Sort() please see version two:
List Version:
public class AlphaNumericComparer : IComparer<string>
{
public int Compare(string lhs, string rhs)
{
if (lhs == null)
{
return 0;
}
if (rhs == null)
{
return 0;
}
var s1Length = lhs.Length;
var s2Length = rhs.Length;
var s1Marker = 0;
var s2Marker = 0;
// Walk through two the strings with two markers.
while (s1Marker < s1Length && s2Marker < s2Length)
{
var ch1 = lhs[s1Marker];
var ch2 = rhs[s2Marker];
var s1Buffer = new char[s1Length];
var loc1 = 0;
var s2Buffer = new char[s2Length];
var loc2 = 0;
// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
s1Buffer[loc1++] = ch1;
s1Marker++;
if (s1Marker < s1Length)
{
ch1 = lhs[s1Marker];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(s1Buffer[0]));
do
{
s2Buffer[loc2++] = ch2;
s2Marker++;
if (s2Marker < s2Length)
{
ch2 = rhs[s2Marker];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(s2Buffer[0]));
// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
string str1 = new string(s1Buffer);
string str2 = new string(s2Buffer);
int result;
if (char.IsDigit(s1Buffer[0]) && char.IsDigit(s2Buffer[0]))
{
var thisNumericChunk = int.Parse(str1);
var thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}
if (result != 0)
{
return result;
}
}
return s1Length - s2Length;
}
}
call like so:
test.sort(new AlphaNumericComparer());
//RESULT
Hello1
Hello2
Hello3
Hello10
Hello11
Hello20
Hello100
Welcome0
Welcome2
World
World3
Array.sort version:
Create class:
public class AlphaNumericComparer : IComparer
{
public int Compare(object x, object y)
{
string s1 = x as string;
if (s1 == null)
{
return 0;
}
string s2 = y as string;
if (s2 == null)
{
return 0;
}
int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
int marker2 = 0;
// Walk through two the strings with two markers.
while (marker1 < len1 && marker2 < len2)
{
var ch1 = s1[marker1];
var ch2 = s2[marker2];
// Some buffers we can build up characters in for each chunk.
var space1 = new char[len1];
var loc1 = 0;
var space2 = new char[len2];
var loc2 = 0;
// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
space1[loc1++] = ch1;
marker1++;
if (marker1 < len1)
{
ch1 = s1[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));
do
{
space2[loc2++] = ch2;
marker2++;
if (marker2 < len2)
{
ch2 = s2[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));
// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
var str1 = new string(space1);
var str2 = new string(space2);
var result = 0;
if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
var thisNumericChunk = int.Parse(str1);
var thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}
if (result != 0)
{
return result;
}
}
return len1 - len2;
}
}
Call like so:
This time test is an array instead of a list.
Array.sort(test, new AlphaNumericComparer())
You can use LINQ combined with regex to ensure that you use only numbers that occur at the end of the string for your secondary ordering
test
.Select(t => new{match = Regex.Match(t, #"\d+$"), val = t})
.Select(x => new{sortVal = x.match.Success
?int.Parse(x.match.Value)
:-1,
val = x.val})
.OrderBy(x => x.val)
.ThenBy(x => x.sortVal)
.Select(x => x.val)
.ToList()

How can i remove ids one by one from querystring in asp.net using c#?

I want remove "ids"one by one querystring from my url. How can i do this ? (using Asp.net4.0 , c#)
Default.aspx?ids=10,2,6,5
I want to remove"ids=6", but language would be the first,middle or last, so I will have this :
Default.aspx?ids=10,2,5,
Step 1. Have your ids in an array by:-
string[] idsarray = Request.QueryString["ids"].ToString().Split(',');
step 2. create a function to remove as per your language
string removeidat(string[] id, string at)
{
string toren = "";
int remat = -1;
if (at=="first")
{
remat = 0;
}
else if (at == "middle")
{
remat = id.Length / 2;
}
else
{
remat = id.GetUpperBound(0);
}
for (int i = 0; i < id.GetUpperBound(0); i++)
{
if (i!=remat)
{
toren += id[i] + ",";
}
}
if (toren.Length>0)
{
toren = toren.Substring(0, toren.Length - 1);
}
return toren;
}
Example : if you want to remove last id your code would be
string[] idsarray = Request.QueryString["ids"].ToString().Split(',');
string newids = removeidat(idsarray , "last")
string strIDs = Request.QueryString["ids"];
if(strIDs != null)
{
string[] ids = strIDs.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries);
var no6 = ids.Where(id => id != "6");
string newUrl = string.Format("Default.aspx?ids={0}", string.Join(",", no6));
Response.Redirect(newUrl);
}

Categories