Add property to an item in a list - c#

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

Related

How can I use a LINQ statement to filter out items that matches one of the words from another List?

I'm trying to get a list of properties of my object except a few ones(who matches a few strings and the ones which are null), the default list looks like follows:
I already filter out the properties which are null, now I want to use LINQ to filter out "TypeId" ,"SubTypeId", "TypeDescription" and "SubTypeDescription", therefore i created a list:
List<string> standardProperties = new List<string> { "TypeId", "TypeDescription", "SubTypeId", "SubTypeDescription" };
My Linq query looks like this atm:
Report reportProperties = item.First();
List<string> standardProperties = new List<string> { "TypeId", "TypeDescription", "SubTypeId", "SubTypeDescription" };
#foreach (var prop in typeof(Report).GetProperties().Where(x => x.GetValue(reportProperties) != null))
{
<GridColumn Field="#prop.Name" AllowEditing="#prop.CanWrite"></GridColumn>
}
Does anyone have an idea how to achieve this?
Thanks
So you have a class Report. This class has zero or more properties, and you want all PropertyInfos of the Report class, except the PropertyInfos of properties Report.TypeId, Report.TypeDescription, etc.
Of course you can check on the names of the properties using strings. The problem of this is that you will only detect errors at runtime. It would be better to compare on propertyInfos:
var reportType = typeof(Report);
var propertiesToIgnore = new PropertyInfo[]
{
reportType.GetProperty(nameof(Report.TypeId)),
reportType.GetProperty(nameof(Report.TypeDescription)),
reportType.GetProperty(nameof(Report.SubTypeId)),
...
}
var propertiesToProcess = reportType.GetProperties()
.Except(propertiesToIgnore);
foreach (var property in propertiesToProcess)
{
// process the property
...
}
Advantage: if someone changes the name of one of the properties, the problem will be detected at compile time, instead of at runtime.

How to compare list of anonymous object with Enum in c#

I am forming List of object as below, Control is List of Enum.
Ex:
public enum Controls
{
Undefined = 0,
[EnumReferenceTypeField(DisplayName = "Edit")]
Edit = 1,
[EnumReferenceTypeField(DisplayName = "Save")]
Save = 2,
}
Constructing actions List is already written code, am not allowed to change.
var actions = new List<object>();
foreach (var control in Controls)
{
actions.Add(new
{
c = (int)control ,
t = control.ToString()
});
}
and checking the condition as below,
if (actions.Exists(a => a == (object)Enums.Controls.Save))
actions.Remove(Enums.Controls.Submit);
Even if i convert Enum to object type the Exists condition not satisfying, even though actions list have Save action. If i mouse over action at runtime it has to values "2" and "Save". i want to check Save is exists and perform some logic.
There are various things wrong here:
If Controls truly is an enum as you have shown, then you cannot enumerate it with
foreach (var control in Controls) // won't work if Controls is an enum type
You can instead use something like:
var controls =
Enum
.GetValues(typeof(Controls))
.Cast<Controls>()
.ToList();
foreach (var control in controls)
...
Since actions is a List<object>, and the items you are adding to it are of anonymous type, you cannot access the members of the items. Either actions must be implicitly typed:
var actions =
controls // as above
.Select(control => new {
c = (int)control ,
t = control.ToString()
}).ToList();
or you need to use a non-anonymous type and cast to it:
class MyAction {
public int c { get; set; }
public string t { get; set; }
public MyAction(Controls control) {
c = (int)control;
t = control.ToString();
}
}
var actions = new List<MyAction>();
foreach (var control in controls)
actions.Add(new MyAction(control));
If Controls is defined how you say, there is no such value as Controls.Submit.
If Controls really is an enum, then it does not make any sense to have a line like:
if (actions.Exists(a => a == (object)Enums.Controls.Save))
because the members of Controls are static and known at compile time. You should be able to reason about them yourself.
More than likely, the code you have posted is incomplete or incorrect in a critical way.
After some analysis I have tried myself and below code is working perfectly.
Created anonymous object from enum like below,
object saveAction= new
{
c = (int)Enums.Controls.Save,
t = Enums.Controls.Save.ToString()
};
object submitAction = new
{
c = (int)Enums.Controls.Submit,
t = Enums.Controls.Submit.ToString()
};
if (actions.Exists(a => a.Equals(saveAction)))
{
actions.Remove(submitAction);
}
Equals only working not "==". Refer below link
http://www.informit.com/articles/article.aspx?p=1237024&seqNum=4

Linq return type conversion

I have a linq query as follows,
var result =
from Record in DBContext.GetAll().
group new { Record.Filed1, Record.Field2} by Record.Field3
into newGroup
select new
{
BodyRegion = newGroup.Key,
ByScanner =
from exam in newGroup
group exam.MaxValue by exam.Model
into myGroup
select myGroup,
ByExam =
from exam in newGroup
group exam.MaxValue by exam.Protocol
into myGroup2
select myGroup2
};
Then I iterate throught them,
foreach (var rec in result)
{
foreach (var byScanner in rec.ByScanner)
{
ProcessResult(byScanner.Key, byScanner.ToList());
}
foreach (var byExam in rec.ByExam )
{
ProcessResult(byExam.Key, byExam.ToList());
}
}
Everything works fine.
But Iwant to move Linq query (first code snippet) to a function, what should be the return type the function?
Return type of a function can not be var. If I give IEnumerable< Object > then while iterating I can't access rec.ByScanner, rec.ByExam because Object doesn't contain them.
How to resolve this issue?
EDIT:
I tried by creating a new class and filling them in that. But Grouping attributes byScanner.Key, byScanner.ToList() are not accessible. How this can be solved?
You are using an Anonymous Type. These shouldn't be passed around methods.
One thing you can do is create (Let's call it 'Record') a class with properties BodyRegion, ByScanner and ByExam and pass IEnumerable<Record>.

MVC Entity Framework get one column as an array

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

Creating a sublist from a parent list

I have a collection of custom objects, dependents. The custom object has about 70 properties. I want to extract just one property, the membernumber. I have the following code, where I am extracting the membernumbers and creating another list:
var memberIDs = (from d in dependents
select new
{
d.MemberNum
});
foreach(var id in memberIDs)
{
string idValue = id.ToString();
}
The problem is that idValue comes as "{ MemberNum = 20044782604 }" instead of just the "20044782604". Please let me know how to resolve it.
Thanks
That's because you are creating a new anonymous type with the MemberNum as a property. Just select it instead.
var memberIDs = from d in dependents
select d.MemberNum;
This will yield an IEnumerable<int> instead of an IEnumerable<AnonymousType> (assuming MemberNum is of type int).

Categories

Resources