I have a list of area object, how to find object value?
List<object> _area = new List<object>();
_area.Add(new { area_pid = _area_pid, info = _area_name });
I need to find area_pid in list if it is not found then it adds a new object.
I have a list of area object, how to find object value?
List<object> _area = new List<object>();
_area.Add(new { area_pid = _area_pid, info = _area_name });
I need to find area_pid in list if it is not found then it adds a new object.
If you can't be bothered creating a full on class for your area (and I don't see why not, it just seems to be a couple of properties, maybe 3 lines of code) you can use a ValueTuple
List<(int area_pid, string area_name)> areas = new List<(int, string)>();
areas.Add((3,"New York"));
areas.Add((4,"New Jersey"));
areas.Add((5,"Chicago"));
//find example
var newAreas = areas.Where(a => a.area_name.StartsWith("New"));
Personally I'm not a fan over creating a dedicated storage class, but it may be of interest to you. There are a c# 7 / .net 4.7 construct by the way
See for more:
https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/
Given
public class Something
{
public Something(string area, string name)
{
Area = area;
Name = name;
}
public string Area { get; set; }
public string Name { get; set; }
}
Usage
Then you could simply use a Where
statement
var somethings = new List<Something>();
somethings.Add(new Something("sad", "bobo"));
var results = somethings.Where(x => x.Area == "asd");
Or if you assume there is only one SingleOrDefault
or FirstOrDefault
var result = somethings.SingleOrDefault(x => x.Area == "asd");
Your can use
foreach(Object item in _area) {
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String yourValue = (String)(pi.GetValue(item, null));
}
But, I suggest your to have a model (Class) to store.
Another option is to use ToList() method for defining _area.
var _area = new []{new { area_pid = _area_pid, info = _area_name}}.ToList();
_area.Add(new { area_pid = _area_pid2, info = _area_name2 });
Now you could use
_area.Where(x=>x.area_pid==1);
Update: Based on comment by Enigmativity,
var _area = new []{new { area_pid = default(int), info = default(string)}}.Take(0).ToList();
_area.Add(new { area_pid = _area_pid2, info = _area_name2 });