MVC Entity Framework get one column as an array - c#

my application is asp.net MVC3 using Entity Framework. I am trying to get a list of one column from a table as an array using the following:
public ActionResult Index()
{
//var list = db.CasesProgresses.ToList();
var SeriesList = GetSeriesList(Learner_ID);
return View();
}
public List<string> GetSeriesList(string item)
{
// get DataTable dt from somewhere.
List<string> sList = new List<string>();
foreach (CasesProgress row in db.CasesProgresses)
{
sList.Add(row[0].ToString());
}
return sList;
}
I get two errors:
Cannot apply indexing with [] to an expression of type 'caseprog.Models.CasesProgress' and
The name 'Learner_ID' does not exist in the current context
Would appreciate your suggestions.

You probably need to read the Property name of your CasesProgress object
Change this
sList.Add(row[0].ToString());
to
sList.Add(row.YourPropertyNameHereWhichIsOfStringType);
If the Property is not of string type, (ex : Integer / decimal ) you may apply ToString() method on that and then add to the string collection.
sList.Add(row.Learner_ID.ToString());
Assuming Learner_ID is a property of CasesProgress class with numeric type.

foreach (CasesProgress row in db.CasesProgresses)
{
sList.Add(row.SomePropertyYouNeed.ToString());
}
if you are using a foreach, there is no [0]. If you were using a normal for (int i =0; i < list.Count; i ++;) then you would be able to do that. But then ofcourse you would have to change the 0 to i, and you would still need to access a property. Well you wouldn't have to do that if your List had a different type, but in your current example you will need to add a String.

The name 'Learner_ID' does not exist in the current context
GetSeriesList(Learner_ID);
Learner_ID - is not defined in your action and you can remove it, because parameter in GetSeriesList(string item) is not used (also remove parameter).
Cannot apply indexing with [] to an expression of type 'caseprog.Models.CasesProgress'
In foreach row is separate item from collection, that's why you shoud access it by property with dot notation row.Property.

Why not just keep it simple and use the 'usual' syntax
var list = db.CasesProgresses.Select(o=>o.YourPropertyName).ToList();
If its an int and you need it as a string list simply replace YourPropertyName with YourPropertyName.ToString() above

Related

how to find an item in c# list

public class LIST
{
public double num;
public double longi;
public double ux;
public double vy;
}
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
L1.ux= // I take l1.ux from stream reader by reading a file and made this
for
L1.vy=.. the other parameters
L1.longi=..
L1.num=....
LIST1.Add(L1)
Here my problem is ı made a list that contains 4 parameters. But ı want to find just one parameter value for instance L1.num how can I take this value from a list?
var indexOfLISTObject = 1 //you need to know which object from LIST1 you want to use
var numParamOfLISTObject = LIST1[indexOfLISTObject].num;
Please Don't name your object LIST. It will create readability issues down the line for you. Name the object what a particular item in your list will represent.
To access a particular property from an item in list you can do following
List l1 = new list();
//Add items ...
//Print property from particular index
Console.WriteLine(l1[index].propertyname);
Put the paremeters inside a list one by one.
in your example you want the parameter num.
List parameterNum = new List();
parameterNum = l1.Select(x => x.Num).ToList();
parameterNum has now the list of Num from l1 list.
If you mean to find/search for a particular value, you could also use System.Linq. For example if you would like to find a member where num is set to 2, you could do this:
LIST1.Where(item=>item.num==2).FirstOrDefault()
According my Understanding If you want to Get objects that contain with specific parameter
then you can use this code
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
var SearchedValue= List1.where(x=>x.num==L1.num).tolist();
if you want just L1.num value then you can use this line (if searched record will 1 then you should use this)
var SearchedValue= List1.where(x=>x.num==L1.num).FirstOrDefault().num;
you can use
LIST1[index].propertyname //index is index of list element and propertyname is the name of property you want to access

How to use dynamic Linq with List<dynamic> object

I have a List of dynamic objects that I am trying to use dynamic Linq on. I am using dynamic objects because I do not know the properties that will be coming into the object. Linq works on my dynamic object, but, to avoid giant hard coding if statements, I would like to use dynamic Linq to search my list. The top half of the code snippet works but I need it to work dynamically so I can create a query string from my properties and filter that way.
public List<dynamic> GetFilteredLocationData(List<dynamic> locationData, string searchTerm){
//Does work
List<dynamic> totalResults = locationData.Where(x => x.Street.ToLower().Contains(searchTerm.ToLower()) ||
x.Street.ToLower().Contains(searchTerm.ToLower()) ||
x.Zip.ToLower().Contains(searchTerm.ToLower()));
//Does not work
var testQueryString = "(Street == \"king\")";
var testResult = locationData.Where(testQueryString);
return totalResults;
}
The runtime error I receive: No property or field 'Street' exists in type 'Object'
That error makes sense as object by default doesn't contain 'Street' but I'd expect the dynamic Linq to behave like the code above it. Is there something I am doing wrong here, or should I take a different approach? I can provide more detail if needed.
Thanks in advance!
Finally I got a working solution! It may not be the most efficient but it works for my needs and allows me to keep the dynamic nature I was hoping to retain. The solution was to drop Linq entirely and use a good old for-each loop. The Important part was the IDictionary which allowed me to search each row for the key value pair. This is the same functionality I was going for, just ditched linq.
public List<dynamic> GetFilteredLocationData(List<dynamic> locationData, string searchTerm){
List<dynamic> totalResults = new List<dynamic>();
List<string> locationProperties = new List<string> {"dynamic properties here, this was filled by call to DB for info pertaining to certain location combined with unique data"}
foreach (var locData in locationData)
{
var currentLoc = locData;
var currentLocDict = (IDictionary<string, object>)currentLoc;
bool containsSearchTerm = CheckIfLocationContainsSearch(currentLocDict, allLocationProperties, searchTerm);
if (containsSearchTerm)
{
totalResults.Add(locData);
}
}
}
public bool CheckIfLocationContainsSearch(IDictionary<string,object> location, List<string> locationProperties, string searchTerm){
foreach (var locProp in locationProperties)
{
if (location[locProp].ToString().ToLower().Contains(searchTerm))
{
return true;
}
}
return false;
}

How to find specific object from list in C#?

How is it possible to find a specific object from a list?
Lets say i have a function that takes an object and a list that contains objects of this type and returns the number at which position the specific object is found.
The only way i could think of a solution is to run the list through with a foreach loop, but isn't there a better way?
Thanks
You can use the IndexOf(T item) method:
myList.IndexOf(myItem);
It returns the index of the first occurrence of the item.
The only way i could think of a solution is to run the list through with a foreach loop
Generally, you need a loop (a for or foreach) to find an object in a list. You could use it directly, or through a function that iterates over list elements, but there is going to be a loop. There is no way around it: unless you know something special about the way the elements of the array are arranged, you have to look at them all.
One case of knowing something special about arrangement of elements is knowing that an array is sorted. If this is the case, and when you know the value of the attribute on which the element is sorted, you can find the element much faster by using binary search.
You could use linq expressions
List.where(condition)
Or
List.Select(condition).FirstOrDefault
Based on search condition it will return the item you want.
You can use method IndexOf or if you use a special condition then you can use method
public int FindIndex(Predicate<T> match);
where match is delegate
public delegate bool Predicate<T>(T obj);
In fact it is similar to standard C++ algorithm std::find_if
To see whether object is there You might just need List<T>.Contains method
It states,
Determines whether an element is in the List.
And you need to use it like List<T>.Contains(T type item) , where T is the same type of List and item you need to compare. In your case it's a the type of Object
And to return the index you can use List<T>.IndexOf Method
Searches for the specified object and returns the zero-based index of the first occurrence within the entire List.
Simple Console program
class Program
{
static void Main(string[] args)
{
MyType a = new MyType() { id = 10 };
MyType b = new MyType() { id = 20 };
MyType c = new MyType() { id = 30 };
List<MyType> testList = new List<MyType>();
testList.Add(a);
testList.Add(b);
Console.WriteLine(testList.Contains(a)); // <= Will return true
Console.WriteLine(testList.Contains(c)); // <= Will return false
Console.WriteLine(testList.IndexOf(a)); // <= will return 0 : the index of object a
Console.ReadKey();
}
}
// A simple class
class MyType
{
private int ID;
public int id
{
get { return ID; }
set { ID = value; }
}
}

Add property to an item in a list

So I'm just starting out with ASP.NET MVC, and I've run into an issue I just can't find an answer to.
I'm grabbing some data from an SQL database, and send it to the view with this code:
var listingsQuery = (from s in db.tblListings select s).OrderBy(s => s.listingID).Skip(100).Take(25);
var listings = listingsQuery.ToList();
return View(listings);
This works great, but I want to add a value in the list of results. Basically what I'm trying to do is something like this:
foreach (var item in listings)
{
this.Add("propertyType", "Home");
}
But obviously that doesn't work. I've tried doing ToArray() instead of ToList() and that got me nowhere.
Do you want to add a new property to each object in the List collection? If so, you can create a new type that inherits from whatever object type is in the list (hover over the listingsQuery variable - the type is inside the <> symbols) and add the new property to it:
public class MyNewType : ExistingTableType
{
public string PropertyType { get; set; }
}
Then inside of your query, project the properties into this new type:
var listingsQuery = (from s in db.tblListings
orderby s.listingID
select new NewType
{
listingID = s.listingID,
someOtherField = s.someOtherField
}
).Skip(100).Take(25);
Now you can cycle through each record and assign a value:
foreach(var record in listings)
{
record.ProperyType = "Home";
}
There are other ways of doing this as well (assuming you're using EF), for example, if you used raw SQL you can cast the result type directly into the new type (without having the map each field), but this should get you started.
If you want to add a new row to your listings collection you need to do listings.Add instead of this.Add
If you want to modify a value in your listing collection then you need to do
foreach(var item in listings)
{
item.PropertyName = value;
}

Problem in converting a generic list<string> or string[] array to datatable

I have the below function
public static DataTable ToTable<T>(this IEnumerable<T> listItem)
{
//Return null if the list is empty
if (listItem == null || listItem.Count() == 0) return null;
//Gets the type of the object
var listType = listItem.First().GetType();
//Initialize a new datatable
var dataTable = new DataTable(listType.Name);
//Create the datatable column names and types
listType.GetProperties().ToList().ForEach(col => dataTable.Columns.Add(col.Name, col.PropertyType));
//Get the datatable column names
var dataTableColumnNames = dataTable.GetDatatableColumnNames();
listItem.ToList().ForEach(item =>
{
//create a new datarow
var dataRow = dataTable.NewRow();
dataTableColumnNames
.Where(propName => listType.GetProperty(propName) != null)
.ToList()
.ForEach(columnName =>
//Exception happens here in the next line
dataRow[columnName] = listType.GetProperty(columnName).GetValue(item, null));
//Add the row to the data table
dataTable.Rows.Add(dataRow);
});
//Commit the changes to the datatable
dataTable.AcceptChanges();
return dataTable;
}
It works great for dictionary object and generic list as List<MyClass> .. but not for
List<string> or string[].
For those I am getting an exception as Parameter count mismatch.
The error is coming at
dataRow[columnName] = listType.GetProperty(columnName).GetValue(item, null));
What is the mistake that is happening?
Please help
Here's the deal. The index operator is actually considered a property when using reflection, hence parameter count mismatch.
If you break into your code and check the properties that are actually being enumerated by GetProperties(), you'll see the "Chars" property. That's the String's index operator. Since you didn't provide an index, you're getting a Parameter Count Mismatch error.
In essence, I assume string doesn't have any properties you want to put in your data table, but rather the string instance IS what you want to put in the data table.
You could create a model to store the string in, with the string as a property on the model, then the string would be stored with your current code. Otherwise, you will need to rethink your table generation algorithm for primitive types.
I hope this helps :)
Because one of the public properties of string is an indexer and you pass null as the index value. So you effectively end up doing this: string[null] which ends up in an exception.
I haven't verified this as I don't have VS available right now so I might be wrong but I'm pretty sure that's the problem.
Update: This question answers how you detect an indexed property: C# Reflection Indexed Properties

Categories

Resources