Search code examples
c#data-dictionary

How to query datatable from a datadictionary for a given id


Hi I have problem in reading a data table which has given id in the dictionary. Any one help me please. Below is my code. I have a dictionary datasourceData I am storing data table. I need to retrieve the datatable stored in the dictionary for the given id.

public Dictionary<Guid, DataTable> dataSourceData { get; set; }

public DataModel()
        {
            dataSourceData = new Dictionary<Guid, DataTable>();
            logger = new BasicFileLogger.Logger();
        }

public DataTable GetDataSourceDescriptionById(Guid piId)
        {
            if (piId == null || piId == Guid.Empty)
                throw new InvalidOperationException("No such datasourcedescriptionId");
            try
            {
                return dataSourceData.Values.Where(db => db.Equals(piId));
            }
            catch (Exception ex)
            {
                logger.WriteException(ex);
                throw new InvalidOperationException(ex.Message);
            }
        }

Help please?


Solution

  • You can simple access it using the key:

    if(dataSourceData.ContainsKey(yourGUID))
        DataTable dt = dataSourceData[yourGUID];
    

    where yourGUID is the GUID you want to access against, you may check if your dictionary contains the GUID key, so you method could be:

    public DataTable GetDataSourceDescriptionById(Guid piId)
            {
                Dictionary<Guid, DataTable> dataSourceData = new Dictionary<Guid, DataTable>();
                if (dataSourceData.ContainsKey(piId))
                {
                    return dataSourceData[piId];
                }
                else
                {
                    InvalidOperationException ex = new InvalidOperationException("No such datasourcedescriptionId"));
                    logger.WriteException(ex);
                    throw ex;
                }
            }