HOW TO MAKE create var array dynamic in C# - 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);

Related

Returning data from foreach data

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

C# Mongo Query In not returning result

I'm having issue with getting back a result when using the Mongo In query. When I've tested the same query in native mongo, it's bringing back the correct result. Im trying to bring back all the ids that match in the temp array.
var temp = new BsonValue [collection.Count()];
for (int i = 0; i < collection.Count(); i++)
{
temp[i] = collection[i].ID;
}
var query = Query.In("ID", temp);
var collection2 = db.GetCollection<TXT>("TXT").Find(query).ToList();
What version of MongoDb's C# driver are you using? It looks like you might be using a deprecated version of the driver.
Here is an example of how we use to use the .In filter in version 2.0.1.27:
var filter = Builders<INVENTTXT>.Filter.In(item => item.ITEMID, temp);
var result = await db.GetCollection<INVENTTXT>("INVENTTXT")
.Find(filter)
.ToListAsync()
.Result;
In the legacy driver, assuming that your INVENTTXT looks something like this:
class INVENTTXT
{
[BsonId]
public ObjectId _id { get; set; }
public String ITEMID { get; set; }
}
Then this works for me to pull the values back:
public static void GetWhereIn()
{
var collection = new List<INVENTTXT>()
{
new INVENTTXT {ITEMID = "52719635"}
};
var temp = new BsonValue[collection.Count()];
for (int i = 0; i < collection.Count(); i++)
{
temp[i] = collection[i].ITEMID;
}
var query = Query.In("ITEMID", collection.Select(c => BsonValue.Create(c.ITEMID)));
var collection2 = db.GetCollection<INVENTTXT>("INVENTTXT").Find(query).ToList();
var count = collection2.Count;
}

How to get value from list string?

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#.

Linq to Entities error

In MVVM, i am getting an entity set from the repository to viewmodel. While trying to access the elements of the entity, it throws an exception:
LINQ to Entities does not recognize the method 'InsurableRisk.Entities.QueriesParameter ElementAt[QueriesParameter](System.Linq.IQueryable`1[InsurableRisk.Entities.QueriesParameter], Int32)' method, and this method cannot be translated into a store expression.
Here is my code:
Repository:
public IQueryable<QueriesParameter> GetParams(int QKey)
{
IQueryable<QueriesParameter> param = (from Q in Context.QueriesParameters
where (Q.QueryKey == QKey)
select Q);
return param;
}
Service:
public IQueryable<QueriesParameter> GetParams(int QKey)
{
return _repository.GetParams(QKey);
}
ViewModel:
paramLabel = new string[] { "ParamLabel1", "ParamLabel2", "ParamLabel3", "ParamLabel4", "ParamLabel5", "ParamLabel6" };
param = new string[] { "Param1", "Param2", "Param3", "Param4", "Param5", "Param6" };
paramVisibility = new string[] { "ParamVisiblity1", "ParamVisiblity2", "ParamVisiblity3", "ParamVisiblity4", "ParamVisiblity5", "ParamVisiblity6" };
paramLabelVisibility = new string[] { "ParamLabelVisiblity1", "ParamLabelVisiblity2", "ParamLabelVisiblity3", "ParamLabelVisiblity4", "ParamLabelVisiblity5", "ParamLabelVisiblity6" };
private Dictionary<int, string> m_queryNames;
private Dictionary<int, string> m_ReadOnlyQueryNames;
private int m_SelectedQueryNames;
public int SelectedQueryNames
{
get
{
return m_SelectedQueryNames;
}
set
{
if (m_SelectedQueryNames != value)
{
m_SelectedQueryNames = value;
OnPropertyChanged("SelectedQueryNames");
var QKey = m_SelectedQueryNames;
var sqlQuery = _service.GetQuery(QKey);
var paramCount = _service.GetParamCount(QKey);
//code to make the run button visible and the parameters to be visible
m_Visibility = true;
IQueryable<QueriesParameter> param = _service.GetParams(QKey);
for (int i = 1; i <= paramCount; i++)
{
OnPropertyChanged(paramLabelVisibility[i]);
OnPropertyChanged(paramVisibility[i]);
QueriesParameter qParam = param.ElementAt(i); <!-- I get the exception here -->
m_LabelName = qParam.ParameterName;
OnPropertyChanged(paramLabel[i]);
//OnPropertyChanged(param[i]);
}
}
}
Any help as in why i am getting this error?
You are getting this error because ElementAt is not supported by LINQ to Entities (indeed, how you will translate it into SQL?). Here is list of Supported and Unsupported LINQ Methods.
You can enumerate over params instead:
IQueryable<QueriesParameter> param = _service.GetParams(QKey);
int i = 1; // btw why you are iterating from index 1? It should be zero!
foreach(var p in param)
{
OnPropertyChanged(paramLabelVisibility[i]);
OnPropertyChanged(paramVisibility[i]);
QueriesParameter qParam = p; // here
m_LabelName = qParam.ParameterName;
OnPropertyChanged(paramLabel[i]);
i++;
}
Another option - move query to client side by calling AsEnumerable() or ToList(). Then Linq to Objects will be used, where you can use ElementAt(index) method or via indexer [index]:
List<QueriesParameter> param = _service.GetParams(QKey).ToList();
//... your code
QueriesParameter qParam = param[i];

Querying the id of an entity using linq

In the following method I am trying to fetch the Username by passing the id value where the ids passed as parameter can be multiple values as in csv's (eg: 1,2) and are returned to the calling function as IEnumerable.
Code Follows as below :
[NonAction]
public static IEnumerable<UserProfile> SearchCMSAdmins(string s)
{
//var searchResults = Entities.UserProfiles.Where(item =>item.UserName.Contains(s));
//return searchResults;
string[] ids = s.Split(',');
IEnumerable<UserProfile> results = null;
IList<UserProfile> user = new List<UserProfile>();
for (int i = 0; i < ids.Length; i++)
{
int id = Convert.ToInt32(ids[i].ToString());
var entity = Entities.UserProfiles.Where(item => item.UserId);
//user.Add(entity);
results = results.Concat(entity);
}
return results;
}
Any help is appreciated.
Try using Contains:
var results = Entities.UserProfiles.Where(item => ids.Contains(item.UserId));
http://msdn.microsoft.com/en-us/library/ms132407.aspx
You can get the id array to be of int type, You can either use int.TryParse or Convert.ToInt32 like:
int[] ids = s.Split(',').Select(r=> Convert.ToInt32(r)).ToArray();
Later you can modify your LINQ query as:
IList<UserProfile> user = Entities.UserProfiles
.Where(item=> ids.Contains(item)).ToList();
This would be like Select * from table where ID in (1,2,3) see Creating IN Queries With Linq to SQL for idea
[NonAction]
public static IEnumerable<UserProfile> SearchCMSAdmins(string s)
{
string[] ids = s.Split(',');
foreach (string idAsString in ids)
{
int id = Convert.ToInt32(idAsString);
var entity = Entities.UserProfiles.Where(item => item.UserId == id);
yield return entity;
}
}
should do it (there should be some validation code too in case the id is not an int or the entity is null)

Categories