Using Lookup in Linq - c#

Need to fetch the first record from Lookup when a condition is satisfied. In below, resId will be key having one or more lists value. In vb, used the below code to fetch the record having resId and record satisfying the below condition. It works perfect.. how can I use the same logic with C#
Lookup<Guid, Class> responseLookup;
result = responseLookup(Guid).FirstOrDefault(
Function(x) catId.Equals(x.catCode)
Tried to convert but was receiving "Method name expected" error

This should work:
responseLookup[Guid].FirstOrDefault(x => catId.Equals(x.catCode))
The => is a lambda-expression. In your case a delegate that excepts a single instance from your list and returns a bool.

Assuming Guid in responseLookup(Guid) is some Guid value, not the type name, the following should work (I suggest using standard naming conventions and refrain from using BCL type names as variable names):
Guid guid = ...;
var result = responseLookup[guid]
.FirstOrDefault(x => catId.Equals(x.catCode));

Related

no parameterless constructor defined for this object in C# using Sqlite-net ExecuteQuery method

I am working with C# application using Sqlite-net. My query should return a single column value, but when i run the query i get the exception. My code is:
foreach(var group in groups)
{
var groupNameCmd = EdgeDatabase._connection.CreateCommand(#"SELECT Name from tblGroup WHERE Id = " + group.Id);
List<string> groupName = groupNameCmd.ExecuteQuery<string>();
}
On the "ExecuteQuery" i get the exception "no parameterless constructor defined for this object".
Since the current answer of akg179 was downvotet, i write down my answer because I was just running into the same issue.
You cannot return a type which is missing a parameterless constructur (like string). Even a projection isn't possible in this case (using LINQ).
To only select a specific column (or multiple columns) you still have to use the right type in your method call (using the generic type):
foreach(var group in groups)
{
var groupNameCmd = EdgeDatabase._connection.CreateCommand(#"SELECT Name from tblGroup WHERE Id = " + group.Id);
List<YourTblGroupType> groupName = groupNameCmd.ExecuteQuery<YourTblGroupType>();
}
You'll now get a list of YourTblGroupType but only the Name property will be set.
And if you really only wanna have the list of strings you can still use the following lambda expression afterwards:
List<string> names = groupName.Select(p => p.Name).ToList()
You have used group.Id while creating your SQL command. This group should be an instance of a class.
Check if there is a parameter less constructor present in the class of which group is an instance of. If not, try adding a parameter less constructor to that class.

how to convert list of strings to list of guids

I have following line of code which creates an list of strings.
List<string> tstIdss = model.Ids.Where(x => x.Contains(entityId)).Select(x => x.Split('_').First()).ToList();
I need to convert it into list of Guids. i.e. List<Guid> PermissionIds.
model.PermissionIds= Array.ConvertAll(tstIdss , x => Guid.Parse(x));
I tried the above way but getting the following error. model.PermissionIds is implemented as following in my model class.
public List<Guid> PermissionIds { get; set; }
Error 3
>>The type arguments for method 'System.Array.ConvertAll<TInput,TOutput>(TInput[], System.Converter<TInput,TOutput>)'
cannot be inferred from the usage.
Try specifying the type arguments explicitly.
You can use Linq's Select and ToList methods:
model.PermissionIds = tstIdss.Select(Guid.Parse).ToList();
Or you can use the List<T>.ConvertAll method:
model.PermissionIds = tstIdss.ConvertAll(Guid.Parse);
I'm not familiar with ConvertAll, but try using Select:
model.PermissionIds = tstIdss.Select(s=>Guid.Parse(s)).ToList();
I have following line of code which creates an list of strings.
I need to convert it into list of Guids.
If your list of strings is safe to parse as Guids, I recommend the answer from #Thomas Leveque.
If your list of strings may contain some non-guids, it is safer to use a TryParse as follows:
Guid bucket = Guid.Empty;
model.PermissionIds = tstIdss.Where(x => Guid.TryParse(x, out bucket)).Select(x => bucket).ToList();
The Where clause will filter out any string which can't be formatted as a Guid.

Cannot convert type 'System.Linq.IQueryable<double?>' to 'float'

I have a table named InventoryItem which consists of columns ItemDescription and Item BalanceQty.I want to fetch the BalanceQty of the ItemName selected in a comboBox.For this,I created a method in my Data Access Layer And passed the string parameter representing the string value of ItemDescription to this method.This has been implemented using Entity Framework.This is how my code looks:
public float GetAvailableQty(string itemName)
{
float availableQty =(from table in context.InventoryItem
where table.ItemDescription == itemName
select table.BalanceQuantity);
return availableQty;
}
But it is giving me the following error-
Cannot convert type 'System.Linq.IQueryable' to 'float'
Where am I going wrong?
Probably you need this:
double availableQty =(from table in context.InventoryItem
where table.ItemDescription == itemName
select table.BalanceQuantity).Sum();
IQueriable returns an expression tree. The result of query like this is a rows set, and it can be materialized to IEnumerate by using of ToList() or implicitly by assigning to IEnumerable. But anyway it will be rows set, not a single value. If you sure the query returns the single one then use .Single() or SingleOrDefault. See other extension methods for IQueriable.
Otherwise, if you need an array then assign result to some IEnumerable variable.
Because your Linq returns an Iqueryable ...
Lets assume you have 3 rows with with an item with 3 different quatities (silly, i know, but think about other things that can have multiple values per item, like colors for a paint). Your linq will return the three quantities, and you're assuming it's a number
You could use First or FirstOrDefault to fetch the first item, or the default value for that object.
In your case, it shouldn't matter, but you should realize how Linq works and what it returns ...
Another example:
let's assume : List numbers = {1,2,3,4,5,6} (let's assume they are ints).
and you do : var small_numbers = numbers.Where(x => x<4)
What you get is something you can then query like: foreach (var small in small_numbers) {...}). The result is not an int.
You could take the first, last, and indeed, that would be an int. But what you get is a collection. so, even if you do: var one_result = numbers.Where(x => x<2), one_result is not an int.

c# order a List<Dictionary<string,object>>

how to order a List<Dictionary<String,object>> the object contains only string
the dictionary is structured as below
[name: mario]
[surname: rossi]
[address: xxxxxx]
[age: 40]
i'd like to order the list of these dictionaries by "age"
may you help me please?
i've tried with:
myList.Select(x => x.OrderBy(y=>y.Value))
it gives me this error: the value isn't a string(ok i aggree with him, it's an object, i've to cast in some way)
but more important is that i can't tell to the "orderby" methods that it must order by age
You want something along the lines of
var sorted = myList.OrderBy(dict => Convert.ToInt32(dict["age"]));
I 've used Convert.ToInt32 defensively because there's a small chance you are using another data type for the age, and casting (unboxing) to the wrong type would throw an exception.
myList.Sort((x,y) => ((int)x["age"]).CompareTo((int)y["age"]));
or similar:
myList.Sort((x, y) => Comparer.Default.Compare(x["age"], y["age"]));
However! It would be much easier if you used a proper type instead of the dictionary; then it would just be:
myList.Sort((x,y) => x.Age.CompareTo(y.Age));

Using LINQ to parse XML into Dictionary

I have a configuration file such as:
<ConfigurationFile>
<Config name="some.configuration.setting" value="some.configuration.value"/>
<Config name="some.configuration.setting2" value="some.configuration.value2"/>
...
</ConfigurationFile>
I am trying to read this to XML and convert it to a Dictionary. I tried coding something liek this but it is obviously wrong as it does not compile.
Dictionary<string, string> configDictionary = (from configDatum in xmlDocument.Descendants("Config")
select new
{
Name = configDatum.Attribute("name").Value,
Value = configDatum.Attribute("value").Value,
}).ToDictionary<string, string>(Something shoudl go here...?);
If someone could tell me how to get this working it would be really helpful. I could always, of course, read it
To give a more detailed answer - you can use ToDictionary exactly as you wrote in your question. In the missing part, you need to specify "key selector" and "value selector" these are two functions that tell the ToDictionary method which part of the object that you're converting is a key and which is a value. You already extracted these two into an anonymous type, so you can write:
var configDictionary =
(from configDatum in xmlDocument.Descendants("Config")
select new {
Name = configDatum.Attribute("name").Value,
Value = configDatum.Attribute("value").Value,
}).ToDictionary(o => o.Name, o => o.Value);
Note that I removed the generic type parameter specification. The C# compiler figures that automatically (and we're using an overload with three generic arguments). However, you can avoid using anonymous type - in the version above, you just create it to temporary store the value. The simplest version would be just:
var configDictionary =
xmlDocument.Descendants("Config").ToDictionary(
datum => datum.Attribute("name").Value,
datum => datum.Attribute("value").Value );
Your call to ToDictionary needs a key and value selector. Starting with that you have, it can be
var dictionary = yourQuery.ToDictionary(item => item.Name, item => item.Value);
It isn't necessary to have the query as you're just doing a projection. Move the projection into the call to ToDictionary():
var configDictionary = xmlDocument.Descendants("Config")
.ToDictionary(e => e.Attribute("name").Value,
e => e.Attribute("value").Value);

Categories