-2

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.

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Donald
  • 551
  • 2
  • 6
  • 22
  • 11
    This is a great use case for not using anonymous objects like this, C# is not JavaScript, if you simply created your self a class to hold this information and not use List you would find your life would be a lost easier – TheGeneral May 14 '19 at 05:01

4 Answers4

5

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/

How to create a List of ValueTuple?

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
4

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");
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

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.

Tan Boon Jun
  • 131
  • 12
0

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 });
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51