Dynamically build a int[] array from the database - c#

I'm trying to build a int[] array from returned values from the database,
Normally for an int[] array that isn't database driven you would do something like this:
int[] arr1 = new int[] { 3, 4, 5 };
my public variable is as follows:
public int[] SelectedItems { get; set; } // Which is used for the multi select list box
I then when retrieving the values do something like this:
model.SelectedItems = (from x in collection select x.Id).ToArray();
but I get the error:
Cannot convert source type 'dynamic[]' to target type 'int[]'
I have googled this error but with no avail.
My collection looks like this:
public class UserActivities
{
public int Id { get; set; }
public string ActivityDesc { get; set; }
}
Update
I'm using dapper.net to retrieve the values so once I've made the call to the DB I then read it as follows:
var activities = sqlCon.Read().ToList();
I use this in two places, first place I display the string description which is shown on the page for the user, the Id's I try to reference and build an array which is used else where in the application.

Your (from x in collection select x.Id) requires an IEnumerable<UserActivities> or IQueryable<UserActivities> as the type for the collection variable. The error you are getting is because collection seems to be an IEnumerable<dynamic>.
Given that you mentioned in your edit and the comments that you are using Dapper.NET and the query is performed using the QueryMultiple method, you will need to get the result set with elements of type UserActivities.
This can be achieved using
var collection = sqlCon.Read<UserActivities>().ToList();
which will extract that result set from the multiple query result.

Related

Slapper.AutoMapper returns only single result from list of objects

I've two POCO-s. A and B.
public class A{
[Slapper.AutoMapper.Id]
public int Id { get; set; }
public B BType { get; set; }
// Rest of the fields
}
public class B{
[Slapper.AutoMapper.Id]
public int Id { get; set; }
public string Name {get;set;}
}
T-SQL Stored Procedure result:
ID B_Id B_Name
1 1 B1
2 2 B2
My code to get List with Dapper is:
List<A> aList = new List<A>();
using (IDbConnection connection = new SqlConnection(GlobalConfig.ConnectionString()))
{
var p = new DynamicParameters();
p.Add("#Id", someId);
// Here debug shows me 2 correct objects inside of var list
var list = connection.Query<dynamic>("[spApp_getBlaBlaByID]", p, commandType: CommandType.StoredProcedure);
// After casting I got only 1
aList =(Slapper.AutoMapper.MapDynamic<A>(list) as IEnumerable<A>).ToList();
}
return aList; // Debugging shows only 1 one of the objects
So, what is wrong with my code? Please help to find mistake.
P.S. I came to C# from Java. Maybe in C# world Slapper.Automapper is not in trend anymore. What is flexible and modern solution to map POCO-s with DAPPER?
To begin with, I do not understand need of Slapper here. Dapper is able to handle this role. So code something like below should work without Slapper.
List<A> list = connection.Query<A>("[spApp_getBlaBlaByID]"......
Second is what mentioned by #orhtej2 in comments. Name of stored procedure ends with "ByID". This convention suggests that it will return single record. Are you sure SP returns multiple records? If yes, above code sample should do. If it returns single record, change above to something like below:
A a = connection.Query<A>("[spApp_getBlaBlaByID]"......

How to add Terms into Terms Query (ElasticSearch NEST C#)?

I'm writing a TermsQuery in NEST. I have created a QueryContainer for it. Here is my code:
QueryContainer qc1 = new TermsQuery()
{
Field = "recordID",
Terms =
};
I want to add int array as Terms and it shows that terms only accept IEnumerable<object>. I have tried converting array to Enumbrable and it's not working.
I just want to know what kind of object Terms accept?
Thanks in advance.
Terms accepts an IEnumerable<object> so it can accept a collection of any objects :) The type to use will depend on the field that you are querying against.
Given the model
public class Document
{
public int Property1 { get; set; }
}
To pass it a collection of int or any other type
var termQuery = new TermsQuery
{
Field = Infer.Field<Document>(d => d.Property1),
Terms = new object[] { 1, 3, 5 }
};

Except in LINQ C#

I have to lists. One that contains all the valid chapter codes(chpt_cd) and their associated appl src codes. i.e the list is
List<ChapterCodeValidationOutput>
The base model class is
public class ChapterCodeValidationOutput
{
public string chpt_cd { get; set; }
public string appl_src_cd { get; set; }
}
The list sample data is ..
chpt_cd aapl_src_cd
------- -----------
07038 C062
07038 C062
06206 C191
And another list contains invalid chapter codes only.
List<string>
only.
And it's sample data is '06206'
I have to find the associated appl_src_cd of the invalid chapter codes list i.e. 'C191' and so on . The returned should be a list only.
Except will not help you in this case.
Assuming that these are the lists:
List<ChapterCodeValidationOutput> list1 = ...
List<string> list2 = ...
Then you can create a lookup from the first list for fast lookup like this:
var lookup = list1.ToLookup(x => x.chpt_cd, x => x.appl_src_cd);
And then use it like this to get the list of corresponding codes:
var result = list2.Select(x => lookup[x].First()).ToList();
I am assuming (since you mentioned in the comments), that if there are duplicate chpt_cd values, the corresponding appl_src_cd values will be equal.

Convert List to List<string>

I have the following problem:
public class AwesomeClass
{
public string SomethingCool { get; set; }
public string SomethingUseless { get; set; }
}
I have a class which contains a number of properties, and I need to convert a list of these classes into a list of strings, where the string represents a property in the class.
List<AwesomeClass> stuff = new List<AwesomeClass>();
//Fill the stuff list with some tings.
List<string> theCoolStuff = //Get only the SomethingCool property in the AwesomeClass list.
The reason why I need to convert this to a list of strings is because I have a method which takes a List as a parameter, but the SomethingCool property contains the data that I need for this list.
Note: I could use a foreach loop on the list and populate the List of strings but I'm looking for a more elegant method, perhaps LINQ can do this for me?
You can simply use Select:
var theCoolStuff = stuff.Select(x => x.SomethingCool).ToList();
What Select does is a projection, it projects each item and transforms (not convert) them into another form.
Note that you can even:
List<string> theCoolStuff = stuff.ConvertAll(x => x.SomethingCool);
because the List<T> has a special "conversion" method :-)
foreach (AwesomeClass member in stuff)
{
theCoolStuff.Add(member. SomethingCool)
}

How to declare and assign value for a class that has array variable?

how to assign value for an array variable when it is declared in different class? Below is the sample codes for easier understanding of my problem:-
// Below is a class customer that has three parameters:
// One string parameter and Two int array parameter
public class Customer
{
public string invoiceFormat { get; set; }
public int [] invoiceNumber { get; set; }
public int [] customerPointer { get; set; }
public Customer(
string invoiceFormat,
int[] invoiceNumber,
int[] customerPointer)
{
this.invoiceFormat = invoiceFormat;
this.invoiceNumber = invoiceNumber;
this.customerPointer = customerPointer;
}
}
// How to assign value for invoiceNumber or customerPointer array in
// different windows form?
// The following codes is executed in windowsform 1
public static int iValue=0;
public static Customer []c = new Customer [9999];
c[iValue] = new Customer(textBox16.Text, invoiceNumber[0].iValue + 1,
customerPointer[0].iValue);
// I have an error that the name 'invoiceNumber and customerPointer'
// does not exist inthe current context
what you have
c[iValue] = new Customer(textBox16.Text, invoiceNumber[0].iValue + 1, customerPointer[0].iValue);
which is completely wrong and is why you get the error : the name 'invoiceNumber and customerPointer' does not exist inthe current context
you never declare any array for invoiceNumber or CustomerPointers. Both of these are members of your class which is where I think you are getting confused. I am not even going to take a guess at what invoiceNumber[0].iValue +1 is to be as an int has no members, its a data type
so to fix this we would do something such as
//create some arrays
int[] invoicesNums = new int[]{1,2,3,4,5};
int[] customerPtrs = new int[]{1,2,3,4,5};
//create a new customer
Customer customer = new Customer("some invoice format", invoicesNums, customerPtrs);
//add the customer to the first element in the static array
Form1.c[0] = customer;
ok so thats how you should do that however, I really think you need to stop and take a deeper look into classes, arrays, data types and OOP as this will save you from a major headache when you get further down the road with your Program.
You are attempting to use a value that does not exist yet. Look at your constructor:
public Customer(string invoiceFormat, int[] invoiceNumber, int[] customerPointer)
{
this.invoiceFormat = invoiceFormat;
this.invoiceNumber = invoiceNumber;
this.customerPointer = customerPointer;
}
This means you need to pass a string, a FULL array of int and another COMPLETE array of int. By attempting to do this:
c[iValue] = new Customer(textBox16.Text, invoiceNumber[0].iValue + 1, customerPointer[0].iValue);
You are calling upon variables that don't exist yet. Think about the word constructor. That creates the object and initializes the internal variables. invoiceNumber[] and customerPointer[] are never assigned by passing another array parameter. This is why you are receiving that error message. If you used your constructor to initialize those arrays and then pass a single invoiceNumber and single customerPointer, which are then added to the initialized array then this would work. However, it sounds like your internal values should not be arrays, then you'd be able to just pass a single int value for each of those parameters.

Categories