Click here to Skip to main content
15,671,201 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a
C#
ObservableCollection<Owner> currentOwner
which has only one record in it.

C#
public int OwnerID { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public char Gender { get; set; }
public DateTime DateOfBirth { get; set; }

C#
DataTable ownerDataTable = new DataTable();
ownerDataTable = ownerDataOperations.Stash_GetOwnerDA(owner, ownerLogin);
currentOwner = new ObservableCollection<Owner>();

foreach (DataRow row in ownerDataTable.Rows)
{
  currentOwner.Add(new Owner()
  {
    OwnerID = (int)row["OwnerID"],
    FirstName = (string)row["FirstName"],
    MiddleName = (string)row["MiddleName"],
    LastName = (string)row["LastName"],
    Gender = (char)row["Gender"],
    DateOfBirth = DateTime.Parse(row["DateOfBirth"].ToString())
 });
}

I just want to get the OwnerID property value from the one record that exists in the collection without using loops.

What I have tried:

I tried LINQ but I know too little about it.
Posted
Updated 1-Feb-23 20:10pm
Comments
Member 15627495 1-Feb-23 15:43pm    
you are lost between 'JSON syntax', and 'members of an Array' and 'OOP'.

the way you load 'currentOwner.add(...)', you're using recursion when : the_var = (type)row[...]
the row[...] is allocated in 'the_var' , then 'the_var' is allocated as members of the array of object Owner.

for OOP , you have to use 'this.OwnerId = row [...]' to fill your object values .

sure your can read your collection with 'n-dimension indexes' -> obsColl[0][0] ( for the first record )

as advise, read again about 'Class' in C# , with 'getters' and 'setters', you'll find the good syntax for your needs.
Gerry Schmitz 1-Feb-23 17:44pm    
If there's only "one record", don't put it in a collection. If you have a collection, you can retrieve the "single" using .First() and assign it to a variable so you can access it directly.

1 solution

It seems to me that you have, at least, three options.



C#
Owner bob = new() { LastName = "Builder", OwnerID = 1 };
ObservableCollection<Owner> currentOwners = new() { bob };
//will throw ArgumentOutOfRange exception if the collection is empty
int idFromIndex = currentOwners[0].OwnerID;
//will return 0 if the collection is empty so it's best not to zero base identity Ids
int idFromLinq = currentOwners.Select(owner => owner.OwnerID).FirstOrDefault();
//will throw InvalidOperationException if the collection is empty.
int idFromLinqA = currentOwners.Select(owner => owner.OwnerID).First();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900