Converting/handling returned IList object - c#

I'm having issues extracting values from a returned IList and populating a combobox in windows.forms. All items in the combobox are listed as System.object.
I have done some testing;
var retList = Services.Get<IWarehouseInfo>().ExecuteSPArray("sp_executesql", dict); <-- method that returns some values.
//Tries to extract value from retlist/which is a IList<object[]> collection.
var strList = (from o in retList select o.ToString()).ToList();
var strList2 = retList.OfType<string>().ToList();
var strList3 = retList.Cast<string>();
var strList4 = retList.Where(x => x != null).Select(x => x.ToString()).ToList(); //All these seem to result in system object.
var bub = strList.ElementAt(2).ToString();
var bob = strList4.ElementAt(2).ToString();
var kupa = strList.ToArray();
var kupo = kupa[2].ToString();
All these fail to extract anything useful.

I thank you all for any beeps given. My mistake was that I thought
that the returned values were in a list of objects. But the result was
an IEnumerable, so I did not check the correct vector.
I added an method extracting the values and returning it in desired format, in this case string.
private static List<string> ToListString(IEnumerable<object[]> inparam)
{
var custNums = new List<string>();
foreach (var row in inparam)
{
if (row[0] != null && row[0] != DBNull.Value)
custNums.Add(row[0].ToString());
}
return custNums;
}

Related

How convert IQueryable to list for showing return data?

I have a variable which is IQueryable and I have parameter in my viewmodel that it shows a differences between my selected day and today the code is:
public async Task<ResultData<HomePlannedRecieptInfo>> GetHomePlannedReciepts(HomePlannedRecieptQuery query)
{
var datelist = new List<DateTime>();
var date = DateTime.Now;
for (var i = 0; i <= 6; i++)
{
datelist.Add(date.AddDays(i));
}
datelist.Add(date);
IQueryable<HomePlannedRecieptInfo> result = context.HomePlannedRecieptInfos.Where(t=>t.Date >= DateTime.Today);
foreach (var item in result.ToList())
{
item.DayDiff = (item.Date.Date - DateTime.Now.Date).TotalDays.ToString();
}
var offset = (query.PageNumber - 1) * query.PageSize;
var psize = query.PageSize;
var countQuery = await result.CountAsync();
var data = result.OrderByDescending(c => c.Date);
return new ResultData<HomePlannedRecieptInfo>
{
CurrentPage = query.PageNumber,
TotalItems = countQuery,
PageSize = query.PageSize,
Data = data.ToList()
};
when I execute the code in foreach I can see the number of days in item.dayDiff but I can't see it when the the data return. Can somebody help me please?
You're calling result.ToList(), but you're just iterating over it in the foreach loop, you're not actually storing it anywhere. This should fix it:
var resultAsList = result.ToList();
foreach (var item in resultAsList)
{
item.DayDiff = (item.Date.Date - DateTime.Now.Date).TotalDays.ToString();
}
...
var data = resultAsList.OrderByDescending(c => c.Date);
That is because every time you materialize a IQueryable the data is taken from the database. You materializing twice in your code. Once in the foreach and once when returning the data in data.ToList(). Hence you have two lists with different items. Since you are changing the data in the first list the second will not receive that data.
You have two possibilities:
Call ToList before the foreach and use the same materialized list for changing the property and returning the same list
Change the get acessor for DayDiff to following public string DayDiff {get => (Date.Date - DateTime.Now.Date).TotalDays.ToString();} Using this has the advantage that you do not have to remind you to set the DayDiff if you query the data on other locations of your code

How can I convert IList<object> to string array?

How can I convert IList objects to string array?
While working on the telegram bot, some difficulties arose. I get a IList<object> from google table with some information. I need to convert this IList<object> to an array of strings. How can I do this?
static void ReadBudgetTypes()
{
var range = $"{settingsSheet}!B3:B";
var request = service.Spreadsheets.Values.Get(SpreadsheetId, range);
var response = request.Execute();
var values = response.Values; // here i get list of objects from google table
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
Console.WriteLine("{0}", row[0]);
}
}
else
{
Console.WriteLine("No data!");
}
}
Assuming cells may not be strings and may (or may not) have null values, you can print for each cell of the row:
// assumes ToString() gives a meaningful string
var listOfStrings = row.Select(x => x?.ToString()).ToList();
foreach(string cell in listOfStrings)
Console.WriteLine(cell);
or the whole row, joined by a separator
Console.WriteLine(string.Join(", ", row);
If you know the cells are strings you can just cast
var listOfStrings = row.Cast<string>().ToList();
// or
var listOfStrings = row.Select(x => (string)x).ToList();
and then repeat either of the above (loop or string.Join).
If items could be null,
var listOfStrings = row.Select(x => (x ?? (object)"").ToString()).ToList();
you can try this:
var tempList=List<string>();
string[] arrayList=null;
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
tempList.Add(row[0]);
}
arrayList=tempList.ToArray();
}
Try something like this:
IList<object> list = new List<object>(){ "something", "something else" };
string[] array = list.Select(item => (String)item).ToArray();

How to get AllJoyn byte[] property

I have an AllJoyn property like this
<property name="DeviceAddresses" type="ay" access="read">
I a Windows 10 UWP app when I try to read it - I get success - but I don't know how to get out the value from the result
Code looks like this:
var vProperty = pInterface.GetProperty(propertyName);
if (vProperty == null) return null;
var result = await vProperty.ReadValueAsync();
if (result.Status.IsSuccess)
{
if (vProperty.TypeInfo.Type == TypeId.Uint8Array)
{
byte[] Erg = result.Value ???
}
}
The property value is created via
object o = Windows.Foundation.PropertyValue.CreateUInt8Array(value);
But I found no way (casting or so) the get the bytes out.
I use DeviceProviders to access AllJoyn methods. It uses
IAsyncOperation<InvokeMethodResult> InvokeAsync(IList<object> #params);
to get the server response. It looks similar to what your ReadValueAsync() returns. But not quite the same. This is how I access the bytes.
InvokeMethodResult result = await MyAllJoynMethod.InvokeAsync(new List<object> { "parameter", 2 });
if (result.Status.IsSuccess)
{
var resultList = result.Values as IList<object>;
foreach (var resultListItem in resultList)
{
var pairs = resultListItem as IList<KeyValuePair<object, object>>;
foreach (var pair in pairs)
{
var key = pair.Key as string; //<- type string taken from MyAllJoynMethod definition
var variant = pair.Value as AllJoynMessageArgVariant;//<- type AllJoynMessageArgVariant taken from MyAllJoynMethod definition (variant)
if (variant.TypeDefinition.Type == TypeId.Uint8Array)
{
var array8 = j as IList<object>;
foreach (byte b in array8)
{
// do something with b
}
}
}
}
}
EDIT: If you do not want to program it yourself you can use OpenAlljoynExplorer. Not sure if byte arrays are actually supported, yet.

Finding all identifiers containing part of the token

I know I can get a string from resources using
Resources.GetIdentifier(token, "string", ctx.ApplicationContext.PackageName)
(sorry, this is in C#, it's part of a Xamarin.Android project).
I know that if my elements are called foo_1, foo_2, foo_3, then I can iterate and grab the strings using something like
var myList = new List<string>();
for(var i = 0; i < 4; ++i)
{
var id = AppContent.GetIdentifier(token + i.ToString(), "string", "package_name");
if (id != 0)
myList.Add(AppContext.GetString(id));
}
My issue is that my token names all begin with "posn." (the posn can denote the position of anything, so you can have "posn.left_arm" and "posn.brokenose"). I want to be able to add to the list of posn elements, so I can't really store a list of the parts after the period. I can't use a string-array for this either (specific reason means I can't do this).
Is there a way that I can use something akin to "posn.*" in the getidentifer call to return the ids?
You can use some reflection foo to get what you want. It is not pretty at all but it works. The reflection stuff is based on https://gist.github.com/atsushieno/4e66da6e492dfb6c1dd0
private List<string> _stringNames;
private IEnumerable<int> GetIdentifiers(string contains)
{
if (_stringNames == null)
{
var eass = Assembly.GetExecutingAssembly();
Func<Assembly, Type> f = ass =>
ass.GetCustomAttributes(typeof(ResourceDesignerAttribute), true)
.OfType<ResourceDesignerAttribute>()
.Where(ca => ca.IsApplication)
.Select(ca => ass.GetType(ca.FullName))
.FirstOrDefault(ty => ty != null);
var t = f(eass) ??
AppDomain.CurrentDomain.GetAssemblies().Select(ass => f(ass)).FirstOrDefault(ty => ty != null);
if (t != null)
{
var strings = t.GetNestedTypes().FirstOrDefault(n => n.Name == "String");
if (strings != null)
{
var fields = strings.GetFields();
_stringNames = new List<string>();
foreach (var field in fields)
{
_stringNames.Add(field.Name);
}
}
}
}
if (_stringNames != null)
{
var names = _stringNames.Where(s => s.Contains(contains));
foreach (var name in names)
{
yield return Resources.GetIdentifier(name, "string", ComponentName.PackageName);
}
}
}
Then somewhere in your Activity you could do:
var ids = GetIdentifiers("action").ToList();
That will give you all the String Resources, which contain the string action.

Filtering a List with an array items

i need to filter a list with strings in an array. Below code doesn't return the expected result.
List<searchModel> obj=//datasource is assigned from database
mystring="city1,city2";
string[] subs = mystring.Split(',');
foreach (string item in subs)
{
obj = obj.Where(o => o.property.city.ToLower().Contains(item)).ToList();
}
As far as you're using Contains, I'd say you could be trying to get
entries, city of which matches any city from mystring
entries, city of which match all cities from mystring
So, having (I simplified searchModel class, having omitted property):
List<searchModel> obj = new List<searchModel>
{
new searchModel{city = "city1"},
new searchModel{city = "city2"},
new searchModel{city = "city3"}
};
var mystring = "city1,city2";
var subs = mystring.Split(',').ToList(); //let it be also List<T>
We can do:
//the 1st option
var orFilter = obj.Where(o => subs.Any(s => o.city.ToLower().Contains(s)))
.ToList();
//the 2nd option
var andFilter = obj.Where(o => subs.TrueForAll(s => o.city.ToLower().Contains(s)))
.ToList();
Then do a simple check
foreach (var o in andFilter)
{
Console.WriteLine(o.city);
}
I'd say that the OP is equal to option 2, not option 1.
I think you want this, or something close - I haven't tested it:
List<searchModel> obj=//datasource is assigned from database
mystring="city1,city2";
string[] subs = mystring.Split(',');
obj = obj.Where(o => subs.Contains(o.property.city.ToLower())).ToList();
What you're currently doing is filtering the list by ALL cities. So you'll only return results where o.property.city equals "city1" and "city2" (and any other cities you might have in the list). So you won't get any results.
To match any city in the list instead, try this:
var myFilteredObj = obj.Where(o => subs.Contains(o.property.city.ToLower()).ToList();
I add this codes of lines, probably will help someone and maybe someone will optimize it:
var jaggedArray = new string[100][];
var i = 0;
jaggedArray[i] = {"first folder","first file","first 5 files","last 5 folder"};
filter = "irs le";
var arrFilters = filter.Split(' ');
foreach (var arrFilter in arrFilters)
{
jaggedArray[i] = jaggedArray[i].Where(p =>p.ToLower().Contains(arrFilter.ToLower())).ToArray();
jaggedArray[i + 1] = jaggedArray[i];
i++;
}
return jaggedArray[i]; //new array after filter
//result: "first file","first 5 files"
var result = obj.Where(piD => subs.Contains(piD.city)).ToList();
The code above will filter the obj List based on the string array.

Categories