Returning data from foreach data - c#

I am trying to return that data from the foreach "hostedId" Can someone help?
public static string GetHostedRecordSet()
{
var request = new ListHostedZonesRequest()
{
MaxItems = "1"
};
var list = client.ListHostedZones(request);
foreach (var hostedId in list.HostedZones)
{
Console.WriteLine("\n Hosted ID is:");
Console.Write(hostedId.Id);
}
return hostedId;
}

It depends. If you want to return the first element:
return list.HostedZones.First().Id; // Not in a loop!
If you want to return several items, change the signature of the method:
public static IEnumerable<string> GetHostedRecordSet()
{
var request = new ListHostedZonesRequest()
{
MaxItems = "1"
};
var list = client.ListHostedZones(request);
return list.HostedZones
.Select(z => z.Id);
}

If you want to return all values as a single string you can concatenate them with a delimiter, such as ',':
public static string GetHostedRecordSet()
{
var request = new ListHostedZonesRequest()
{
MaxItems = "1"
};
var list = client.ListHostedZones(request);
StringBuilder result = new StringBuilder();
foreach (var hostedId in list.HostedZones)
{
result.Append(hostedId.Id).Append(",");
}
return result.ToString(0, Math.Max(0, result.Length - 1);
}

Related

Extract number from a GUID

Is there any possiblity to extract only the numbers from a GUID? I'm trying to achieve this because I don't want to display the GUID in a form, but the numbers within, which also are unique.
You can use IsDigit to get only the numbers
var guidstring = Guid.NewGuid().ToString("N");
var getNumbers = (from t in guidstring
where char.IsDigit(t)
select t).ToArray();
DEMO
public string GetNumbersFromGuid(Guid Item)
{
var result = string.Empty;
var guidArray = Item.ToString().ToCharArray();
int n;
foreach (var item in guidArray)
{
if (int.TryParse(item.ToString(), out n) == true)
{
result += item.ToString();
}
}
return result;
}
Call it like:
var MyValue = GetNumbersFromGuid(Guid.NewGuid());

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);

Sort Array on on Value Difference

I Have An Array,for example
string[] stArr= new string[5] { "1#3", "19#24", "10#12", "13#18", "20#21" };
i want to sort this array on
3-1=2;
24-19=5;
12-10=2;
18-13=5;
21-20=1;
and the sorting result should be like
string[] stArr= new string[5] { "20#21", "1#3", "10#12", "13#18", "20#21" };
I have to find the solution for all possible cases.
1>length of the array is not fixed(element in the array)
2>y always greater than x e.g x#y
3> i can not use list
You can use LINQ:
var sorted = stArr.OrderBy(s => s.Split('#')
.Select(n => Int32.Parse(n))
.Reverse()
.Aggregate((first,second) => first - second));
For Your Case:
stArr = stArr.OrderBy(s => s.Split('#')
.Select(n => Int32.Parse(n))
.Reverse()
.Aggregate((first,second) => first - second)).ToArray();
try this
string[] stArr = new string[5] { "1#3", "19#24", "10#12", "13#18", "20#21" };
Array.Sort(stArr, new Comparison<string>(compare));
int compare(string z, string t)
{
var xarr = z.Split('#');
var yarr = t.Split('#');
var x1 = int.Parse(xarr[0]);
var y1 = int.Parse(xarr[1]);
var x2 = int.Parse(yarr[0]);
var y2 = int.Parse(yarr[1]);
return (y1 - x1).CompareTo(y2 - x2);
}
Solving this problem is identical to solving any other sorting problem where the order is to be specified by your code - you have to write a custom comparison method, and pass it to the built-in sorter.
In your situation, it means writing something like this:
private static int FindDiff(string s) {
// Split the string at #
// Parse both sides as int
// return rightSide-leftSide
}
private static int CompareDiff(string a, string b) {
return FindDiff(a).CompareTo(FindDiff(b));
}
public static void Main() {
... // Prepare your array
string[] stArr = ...
Array.Sort(stArr, CompareDiff);
}
This approach uses Array.Sort overload with the Comparison<T> delegate implemented in the CompareDiff method. The heart of the solution is the FindDiff method, which takes a string, and produces a numeric value which must be used for comparison.
you can try the following ( using traditional way)
public class Program
{
public static void Main()
{
string[] strArr= new string[5] { "1#3", "19#24", "10#12", "13#18", "20#21" };
var list = new List<Item>();
foreach(var item in strArr){
list.Add(new Item(item));
}
strArr = list.OrderBy(t=>t.Sort).Select(t=>t.Value).ToArray();
foreach(var item in strArr)
Console.WriteLine(item);
}
}
public class Item
{
public Item(string str)
{
var split = str.Split('#');
A = Convert.ToInt32(split[0]);
B = Convert.ToInt32(split[1]);
}
public int A{get; set;}
public int B{get; set;}
public int Sort { get { return Math.Abs(B - A);}}
public string Value { get { return string.Format("{0}#{1}",B,A); }}
}
here a working demo
hope it will help you
Without LINQ and Lists :) Old School.
static void Sort(string [] strArray)
{
try
{
string[] order = new string[strArray.Length];
string[] sortedarray = new string[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
string[] values = strArray[i].ToString().Split('#');
int index=int.Parse(values[1].ToString()) - int.Parse(values[0].ToString());
order[i] = strArray[i].ToString() + "," + index;
}
for (int i = 0; i < order.Length; i++)
{
string[] values2 = order[i].ToString().Split(',');
if (sortedarray[int.Parse(values2[1].ToString())-1] == null)
{
sortedarray[int.Parse(values2[1].ToString())-1] = values2[0].ToString();
}
else
{
if ((int.Parse(values2[1].ToString())) >= sortedarray.Length)
{
sortedarray[(int.Parse(values2[1].ToString())-1) - 1] = values2[0].ToString();
}
else if ((int.Parse(values2[1].ToString())) < sortedarray.Length)
{
sortedarray[(int.Parse(values2[1].ToString())-1) + 1] = values2[0].ToString();
}
}
}
for (int i = 0; i < sortedarray.Length; i++)
{
Console.WriteLine(sortedarray[i]);
}
Console.Read();
}
catch (Exception ex)
{
throw;
}
finally
{
}

Linq query to take the value from Array with matching sub string value

I have a string - filterArg and array of string - arrayColDef as shown in below code. I am trying to split the string filterArg by |~| and trying to get the value from filterArg by matching arrayColDef value.
Can any one let me know how to get the value ToDo commented in the code
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
string filterArg = "ZipCode=2130|~|ZipPlace=KNAPPER";
string[] arrayColDef = { "ZipCode", "Space", "ZipPlace" };
foreach (var item in arrayColDef)
{
var key = item;
var value = filterArg.Split(new string[] { "|~|" }, StringSplitOptions.RemoveEmptyEntries);//TODO: here value should hold = 2130 for first itteration
ht.Add(item, value);
}
}
I think you get complicated iterating over arrayColDef, it's easier to iterate through splited string and extract the values.
You can do something like below.
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
string filterArg = "ZipCode=2130|~|ZipPlace=KNAPPER";
string[] arrayColDef = { "ZipCode", "Space", "ZipPlace" };
var properties = filterArg.Split(new string[] { "|~|" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var property in properties)
{
var nameValue = property.Split(arrayColDef, StringSplitOptions.RemoveEmptyEntries);
var item = property.Split('=').First(); // get key
var value = nameValue.First().TrimStart('='); // get value
ht.Add(item, value);
}
}
Hashtable ht = new Hashtable();
string filterArg = "ZipCode=2130|~|ZipPlace=KNAPPER";
string[] arrayColDef = { "ZipCode", "Space", "ZipPlace" };
var filterArr = filterArg.Split(new string[] { "|~|" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split('='));
foreach (var item in arrayColDef)
{
var key = item;
var v = filterArr.FirstOrDefault(x => x[0] == item);
if (v != null&&v.Length>1)
{
ht.Add(item, v[1]);
}
}
foreach (var key in ht.Keys)
{
Console.WriteLine("Key:{0} Value:{1}", key, ht[key]);
}
Space has been ignored
The filter split in
var value = filterArg.Split(new string[] { "|~|" }, StringSplitOptions.RemoveEmptyEntries);//TODO: here value should hold = 2130 for first itteration
returns an array. You can get the final value by filtering and replacing with linq:
string finalValue = value.Where(m => m.Contains(item)).Select(m => m.Replace(item+"=","")).FirstOrDefault();
The value, then, is in finalValue variable.
Greetings

Foreach loop for three List<string>

I want to loop through three List<string>. I'm sending ajax request containing 3 parameter as Array.
This is my WebMethod.
public string saveEachTask(string imageData, string desc, string tid)
{
var imglist = imageData.Split(',').ToList();
var desclist = desc.Split(',').ToList();
var idlist = tid.Split(',').ToList();
// here i want a foreach loop for above three list
return "Saved Succesfully";
}
Edit: in loop how can I identity which string is for img, desc and id
Any Help appreciated.
Perhaps something like this:
foreach (var list in new[] {imglist, desclist, idlist})
{
foreach (var s in list)
{
}
}
Use one loop and each iteration process each list.
public string saveEachTask(string imageData, string desc, string tid)
{
var imglist = imageData.Split(',').ToList();
var desclist = desc.Split(',').ToList();
var idlist = tid.Split(',').ToList();
int maxLength = Math.Max(imglist.Count, Math.Max(desclist.Count, idlist.Count));
for (int i = 0; i < maxLength; ++i)
{
string imgItem = (i < imglist.Count ? imglist[i] : null);
string descItem = (i < desclist.Count ? desclist[i] : null);
string idItem = (i < idlist.Count ? idlist[i] : null);
// TODO: Process imgItem, descItem, idItem
}
return "Saved Succesfully";
}
If you need to handle everything the same way in your loop, you could try:
foreach(var s in imglist.Union(desclist.Union(idlist)))
{
// do something with the string
}

Categories