Select from one dictionary with a second dictionary - c#

I have 2 dictionaries List<Dictionary<string, object>> like this:
[{"Id":"2","FirstName":null,"MiddleName":null,"LastName":null,"Birthday":null,"Username":null,"Password":null,"LastLogin":null,"CreateDateTime":null,"UpdateDateTime":null,"Blocked":null,"HasOrders":null}]
and have a Dictionary like this Dictionary<string, string> for filter
var dict = new Dictionary<string, object>
{
{ "Username", "myUsername" },
{ "Password", "myPassword" }
};
My question is how I can filter out within the first List the records with help of the second list.
Please note that I need a where statement with 2 or 3 dynamic keys/values in the second list. There are a lot of records in these JSON structures.
It be great if somebody can point me to the right direction.
--UPDATE--
something like as I want to have, but than without the foreach:
foreach(Dictionary<string, object> v in Data)
{
v.Where(x =>
x.Key.Contains(nList.Where(n => n.Key == x.Key && n.Value = x.Value)));
}
I have no idea on how todo this in LINQ

I suggest you do this in couple of steps. First step, obviously would be to convert the List> structure to a List. Handling it as Collection of Dictionary is not a good approach.
public class UserPass
{
public string Username{get;set;}
public string Password{get;set;}
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime? Birthday { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public DateTime? LastLogin { get; set; }
public DateTime? CreateDateTime { get; set; }
public DateTime? UpdateDateTime { get; set; }
public bool? Blocked { get; set; }
public bool? HasOrders { get; set; }
}
For example,
var dictionary1 = new Dictionary<string,object>()
{
["Id"]="2",
["FirstName"]=null,
["MiddleName"]=null,
["LastName"]=null,
["Birthday"]=null,
["Username"]="anuviswan",
["Password"]="password",
["LastLogin"]=null,
["CreateDateTime"]=null,
["UpdateDateTime"]=null,
["Blocked"]=null,
["HasOrders"]=null
};
var dictionary2 = new Dictionary<string,object>()
{
["Id"]="3",
["FirstName"]=null,
["MiddleName"]=null,
["LastName"]=null,
["Birthday"]=null,
["Username"]="user1",
["Password"]=null,
["LastLogin"]=null,
["CreateDateTime"]=null,
["UpdateDateTime"]=null,
["Blocked"]=null,
["HasOrders"]=null
};
var dataList= new List<Dictionary<string,object>>
{
dictionary1,dictionary2
};
var dict1 = new Dictionary<string, object>
{
{ "Username", "myUsername" },
{ "Password", "myPassword" }
};
var dict2 = new Dictionary<string, object>
{
{ "Username", "anuviswan" },
{ "Password", "password" }
};
var filterList = new List<Dictionary<string,object>> {dict1, dict2};
var dataObjectList = dataList.Select(x=> new User
{
Id = Convert.ToInt32(x[nameof(User.Id)]),
Username = Convert.ToString(x[nameof(User.Username)]),
Password = Convert.ToString(x[nameof(User.Password)]),
});
var filterObjectList = filterList.Select(x=>
new UserPass
{
Username = Convert.ToString(x[nameof(UserPass.Username)]),
Password = Convert.ToString(x[nameof(UserPass.Password)]),
});
With the new Lists in place, you can query as
var result =dataObjectList.Join(filterObjectList,
d=>d.Username,
f=>f.Username,
(x,y)=> new
{
Data = x,
Filter=y
})
.Where(x=>x.Data.Username.Equals(x.Filter.Username)
&& x.Data.Password.Equals(x.Filter.Password))
.Select(x=>x.Data);;

Related

get data from json array string to an string variable

I get from another app an HTTP request with a JSON payload like this:
{
"reportName": "myfile",
"type_1": "pdf",
"paramm": [
{ "REF": "value1"},
{ "whatevervalue2": "whatevervalue2" }
]
}
I receive the data and try to process it. I created a class to get the data from the JSON:
public class ReportId
{
public string reportName { get; set; }
public string type_1 { get; set; }
public object[] paramm { get; set; }
}
And here is the method where I process all the data on the API controller:
[HttpPost]
public IActionResult generate([FromBody] ReportId jsonResult)
{
try
{
var reportName = jsonResult.reportName;
var type = jsonResult.type_1;
var recParam = jsonResult.paramm;
//....
List<ReportParameter> parameters = new List<ReportParameter>();
foreach (var t in recParam)
{
string[] paramName;
paramName = t.ToString().Split(":");
parameters.Add(new ReportParameter()
{
Name = paramName[0],
Labels = new List<string>() { paramName[1] },
Values = new List<string>() { paramName[1] }
});
}
reportWriter.SetParameters(parameters);
//....
}
catch
{
return null;
}
}
I got no problems with reportName and type_1 but on paramm it gets kinda wonky. I need to get the values of that array from the JSON. I do manage to get them, but with "all the format". For example, after the split on the first one I would get:
"{\r\n \"REF\""
" \"value1\"\r\n}"
Is there any more elegant way to get the values from that paramm array without having to replace the characters that are not part of the "real" string?
Thanks in advance.
[EDIT for clarification]
On the JSON I'll get multiple parameters:
"paramm": [
{ "parameter1": "value1" },
{ "parameter2": "value2" },
{ "parameter3": "value3" }
]
The parameter name could be any word and the value could be any as well. Those parameters are being sent to an RDL to filter some queries, so I need to get the name (parameter1, 2, 3...) and its value and add it as a parameter on the iteration of each.
Yes, there is an easier way.
In your ReportId class, change the paramm member to be a List<Dictionary<string, string>> instead of object[].
public class ReportId
{
...
public List<Dictionary<string, string>> paramm { get; set; }
}
Then, in your generate method you can just get the key and value from each dictionary instead of needing to do string manipulation:
List<ReportParameter> parameters = new List<ReportParameter>();
foreach (var dict in recParam)
{
var kvp = dict.First();
parameters.Add(new ReportParameter()
{
Name = kvp.Key,
Labels = new List<string>() { kvp.Value },
Values = new List<string>() { kvp.Value }
});
}
I guess, Your ReportId class should be like this. I hope this will work.
public partial class ReportId
{
[JsonProperty("reportName")]
public string ReportName { get; set; }
[JsonProperty("type_1")]
public string Type1 { get; set; }
[JsonProperty("paramm")]
public Paramm[] Paramm { get; set; }
}
public partial class Paramm
{
[JsonProperty("REF", NullValueHandling = NullValueHandling.Ignore)]
public string Ref { get; set; }
[JsonProperty("whatevervalue2", NullValueHandling = NullValueHandling.Ignore)]
public string Whatevervalue2 { get; set; }
}

Adding data from one list to another using linq

I need to populate a dropdown in my UI and hence added List object to the view model in my c# application. I am fetching the data in my controller code for the dropdown. What's the best way to assign data to the viewmodel object. Is linq an option?
I basically need to assign fundclasses to fundTrackRecord.FundClass
The main Viewmodel:
public class FundPerformanceVM
{
public FundPerformanceVM()
{
TrackRecord = new List<TrackRecordVM>();
}
public int FundId { get; set; }
public string FundName { get; set; }
public List<FundClassVM> FundClass { get; set; }
public string BenchmarkName1 { get; set; }
public string BenchmarkName2 { get; set; }
public List<TrackRecordVM> TrackRecord { get; set; }
public List<Tuple<string, string, string>> FundStatistics { get; set; }
}
public class FundClassVM
{
public int FundClassId { get; set; }
public string FundClass { get; set; }
}
Controller code:
var service = GetViewService<V_LEGAL_FUND_CLASS_SUMMARY>();
foreach (KeyValuePair<int, IEnumerable<FUND_PERFORMANCE>> entry in allPerformance)
{
var fundClasses = service.GetAll().Where(x => x.FUND_ID == entry.Key).Select(x => new { x.LEGAL_FUND_CLASS_ID, x.LEGAL_FUND_CLASS}).ToList();
var fundTrackRecord = new FundPerformanceVM();
fundTrackRecord.FundClass = ??;
If I understood correctly the structure of your model, you can try this:
fundTrackRecord.FundClass = fundClasses.Select(fc => new FundClassVM
{
FundClassId = fc.LEGAL_FUND_CLASS_ID,
FundClass = fc.LEGAL_FUND_CLASS
}).ToList();
You can also do this directly, replacing the code:
var fundClasses = service.GetAll().Where(x => x.FUND_ID == entry.Key).Select(x => new { x.LEGAL_FUND_CLASS_ID, x.LEGAL_FUND_CLASS}).ToList();
var fundTrackRecord = new FundPerformanceVM();
With:
var fundTrackRecord = new FundPerformanceVM();
fundTrackRecord.FundClass = service.GetAll().
Where(x => x.FUND_ID == entry.Key).
Select(fc => new FundClassVM
{
FundClassId = fc.LEGAL_FUND_CLASS_ID,
FundClass = fc.LEGAL_FUND_CLASS
}).ToList();

How to find a specific value in an IDictionary<string, object>?

This IDictionary<string, object> contains user data I'm logging into mongodb. The issue is the TValue is a complex object. The TKey is simply the class name.
For example:
public class UserData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Admin NewAdmin { get; set; }
}
public class Admin
{
public string UserName { get; set; }
public string Password { get; set; }
}
Currently, I'm trying to iterate through the Dictionary and compare types but to no avail. Is there a better way of doing this or am I missing the mark?
var argList = new List<object>();
foreach(KeyValuePair<string, object> kvp in context.ActionArguments)
{
dynamic v = kvp.Value;
//..compare types...
}
Just use OfType<>(). You don't even need the key.
public static void Main()
{
var d = new Dictionary<string,object>
{
{ "string", "Foo" },
{ "int", 123 },
{ "MyComplexType", new MyComplexType { Text = "Bar" } }
};
var s = d.Values.OfType<string>().Single();
var i = d.Values.OfType<int>().Single();
var o = d.Values.OfType<MyComplexType>().Single();
Console.WriteLine(s);
Console.WriteLine(i);
Console.WriteLine(o.Text);
}
Output:
Foo
123
Bar
Link to Fiddle

How to Convert List<T> to BsonArray to save a MongoDB Document

I'm having an Model Class, I need to Save it in a MongoDB Collection.
My Model Class:
public Class Employee
{
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
}
public Class Mobile
{
public string MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}
The Values are
Employee EmpInfo = new Employee()
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>()
{
{ MobNumber = "55566610", IsPreferred = true },
{ MobNumber = "55566611", IsPreferred = false },
}
}
BsonDocument _employee = new BsonDocument()
{
{ "Emp_ID", EmpInfo.EmpID },
{ "Emp_Name", EmpInfo.EmpName },
{ "Emp_Mobile", new BsonArray (EmpInfo.EmpMobile.Select(m => new
{
MobID = new ObjectId(),
MobNumber = m.MobNumber,
IsPreferred = m.IsPreferred
})) }
};
var collection = _database.GetCollection<BsonDocument>("EmployeeInfo");
collection.InsertOne(_employee);
I wish to save the above EmpInfo of type Employee in a MongoDB. But I can't able to create a BsonDocument. Kindly assist me is there is anything wrong in the above code. If yes kindly assist me.
there is no need to serialize to bson document
You can use TYPED collection and just insert data
Please see attached code snipet with updated class structure
void Main()
{
// To directly connect to a single MongoDB server
// or use a connection string
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collectionEmpInfo = database.GetCollection<Employee>("Employee");
Employee EmpInfo = new Employee
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>
{
new Mobile{ MobNumber = "55566610", IsPreferred = true, MobID = ObjectId.GenerateNewId() },
new Mobile{ MobNumber = "55566611", IsPreferred = false, MobID = ObjectId.GenerateNewId() },
}
};
collectionEmpInfo.InsertOne(EmpInfo);
var empList = collectionEmpInfo.Find(new BsonDocument()).ToList();
empList.Dump(); //dump is used in linqPad
}
public class Employee
{
public ObjectId Id { get; set; }
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
}
public class Mobile
{
public ObjectId MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}
In addition to answer above, I can suggest following code if you want to deal directly with Bson for some reason:
BsonDocument _employee = new BsonDocument()
{
{ "Emp_ID", EmpInfo.EmpID },
{ "Emp_Name", EmpInfo.EmpName },
{ "Emp_Mobile", BsonArray.Create(EmpInfo.EmpMobile.Select(m => new BsonDocument()
{
{ "MobID" , new ObjectId() },
{ "MobNumber", m.MobNumber },
{ "IsPreferred", m.IsPreferred }
})) }
};
The reason of the error you've got is that BsonArray.Create creates an array of values, not an array of objects. See this question for details.

Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.ICollection<System.Web.Mvc.SelectList>'

I am trying to add some values into my SelectList data member in my object but I get an error
public ActionResult Create()
{
var paf = new ProductAddForm();
paf.Sizes = new SelectList(m.GetProductSizes());
paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");
return View(paf);
}
that is my creat function, and the paf.Sizes / paf.Suppliers code does not work.
My productaddform class:
public class ProductAddForm
{
public double MSRP { get; set; }
public string Name { get; set; }
public string ProductId { get; set; }
public ICollection<SelectList> Sizes { get; set; }
public ICollection<SelectList> Suppliers { get; set; }
public string UPC { get; set; }
}
And my methods in my manager.cs
public IEnumerable<SupplierList> GetAllSuppliersList()
{
var fetchedObjects = ds.Suppliers.OrderBy(n => n.Name);
var Suppliers = new List<SupplierList>();
foreach (var item in fetchedObjects)
{
var s = new SupplierList();
s.Name = item.Name;
s.Id = item.Id;
Suppliers.Add(s);
}
return (Suppliers);
}
public List<string> GetProductSizes()
{
return new List<string>() { "Small", "Medium", "Large" };
}
Whats wrong?
Suppliers is a collection of SelectList. So you need to Add item into the collection
Change
paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");
to
paf.Suppliers.Add(new SelectList(m.GetAllSuppliersList(), "Id", "Name"));

Categories

Resources