Josh Rice
Josh Rice

Reputation: 47

How to get a key value pair out of an array of objects

Attempt 2 result

I have two tables in the db table one "DocumentFieldValues" that has 2 columns FieldId and Value and table two "Field" that has primary key FieldId and FieldName

I know the FieldName beforehand and I want to make they a Key. there are about 100 key/value pairs that will be in this.

Attempt 1 

   var attempt1= db.DocumentFieldValues.Where(x => x.PolicyDocumentId == id).Include(x => x.Field ).ToList();

Attempt 2

        var documentFieldValues = this.db.DocumentFieldValues.Where(x => x.PolicyDocumentId == id).ToArray();

        var bindingStringAndValue = from documentFieldValue in documentFieldValues
                       join field in this.db.Fields on documentFieldValue.FieldId equals field.FieldId
                       select new {  field.BindingString,  documentFieldValue.Value } ;

I basically need to be able to do data.FieldName and retrieve the value on the front end using a jQuery ajax call to the back end just need to pass this data back in the correct format.

Any help is very much appreciated.

I just made this and this works but is it the best way to go about it ? I only got 4 months experience on the job and only 1-year self-taught none with backend code so dont hate lol I feel like performance wise this is pretty bad

    IDictionary<string, string> dict = new Dictionary<string, string>();

        foreach (var item in bindingStringAndValue)
        {
            dict.Add(item.BindingString, item.Value);
        }

Attempt 4 this is the best way I came across now thanks @Orel Eraki

var dict = db.DocumentFieldValues .Where(dfv => dfv.PolicyDocumentId == id).Include(dfv => dfv.Field) .ToDictionary(dfv => dfv.Field.BindingString, dfv => dfv.Value);

Upvotes: 1

Views: 1417

Answers (1)

Orel Eraki
Orel Eraki

Reputation: 12196

You actually did a good job.

You can do the following if you want it map your values into a Dictionary<string, string>.

var dict = db.DocumentFieldValues
    .Where(dfv => dfv.PolicyDocumentId == id)
    .ToDictionary(dfv => dfv.Field.BindingString, dfv => dfv.Value);

Upvotes: 1

Related Questions