I have the below
var deptRecs= DepartmentRecords; //it is of type IEnumerable<Department>
var deptIDs= new string[] { "1", "2" };
var result = deptIDs.Intersect(?????)
I want to figure out the common department id's. What will sit in the predicate of Intersect?
Use the following instead of Intersect:
deptRecs.Where(d=>deptIDs.Contains(d.DeptId))
For intersect you need same types of entities.
Hope it helps...
Thanks.
You can use Where with Contains instead of Intersect:
var result = deptRecs.Where(x => deptIDs.Contains(x.Id)).ToList();
Assuming Id property of int type on Department class it is enough to filter them with Contains() operation
var result = deptRecs.Where(r=>deptIDs.Contains(r.Id.ToString()))
The Enumerable.Intersect expects argument of the same type. Thus, to perform a set intersection, as you are trying to pass in an array of string, an example can be
DepartmentRecords.Select(i=>i.DepartmentName).Intersect(deptIDs);
I am assuming you have a DepartmentName property of type string. Performing a selection operation returns an IEnumerable<string>. Then I am passing in the array, which will return the set intersection of the two enumerables.
Related
I have casted different type of IEnumerables and passed them in a list.
combinedAll = ((TypeOneIenumerable).Cast<object>()).ToList().Concat(((TypeTwoIenumerable).Cast<object>())).Concat(((TypeThreeIenumerable).Cast<object>()));
And I am retrieving this list as
var combined = (IEnumerable<object>)value;
Now,
I want to separate IEnumerables based upon their specific types.
I am looking to do something like this:
var getBackTypeOneIenumerable = (IEnumerable<TypeOneIenumerable>)value;
So that I can perform Select/Where on getBackTypeOneIenumerable.
You can use Enumerable.OfType which filters and casts:
IEnumerable<TypeOneIenumerable> getBackTypeOneIenumerable = combinedAll.OfType<TypeOneIenumerable>();
Btw, your ToList call in your query is redundant, it will create a new list for no reason.
You can have everything together in this way:
IEnumerable<TypeOneIenumerable> getBackTypeOneIenumerable = TypeOneIenumerable.OfType<TypeOneIenumerable>()
.Concat(TypeTwoIenumerable.OfType<TypeOneIenumerable>())
.Concat(TypeThreeIenumerable.OfType<TypeOneIenumerable>());
I am using Entity Framework with
var result = db.Database.SqlQuery<object>(dynamicSQLString);
var res = result.ToList();
Where dynamicSQLString can be anything... can return a "count()", can be a select with a list of rows.... etc.... there is no way to match it with a known class type. So I thought of using "object".
I would like to know if this is the way to go, and if it is, how can I "convert" the result into a "string"...... ?
Is this even possible?
Update #1
var t1 = result.GetType(); //System.Data.Entity.Internal.InternalSqlQuery
var res = result.ToList();
var first = res.First();
var t2 = first.GetType(); // System.Object
If I do a count on "res" I get the expected number of rows, but I do NOT see a way to get the "property names" of this object/dynamic row, neither it's values.
Update #2
I've found a "similar" example, but in there the person knows exactly the parameters/types the select will return.
http://www.codeproject.com/Articles/206416/Use-dynamic-type-in-Entity-Framework-4-1-SqlQuery
you can't convert the result into string unless your SQL query
(in this case dynamicSQLString)
return premitive primitive such as
"select name from customers" that return a string result for each row in database
You could use the dynamic type instead:
http://msdn.microsoft.com/en-us/library/dd264736.aspx
However you will need to do some casting on it before you can put it into a list.
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# Array, How to make data in an array distinct from each other?
For example
string[] a = {"a","b","a","c","b","b","c","a"};
how to get
string[]b = {"a","b","c"}
Easiest way is the LINQ Distinct() command :
var b = a.Distinct().ToArray();
You might want to consider using a Set instead of an array. Sets can't contain duplicates so adding the second "a" would have no effect. That way your collection of characters will always contain no duplicates and you won't have to do any post processing on it.
var list = new HashSet<string> { };
list.Add("a");
list.Add("a");
var countItems = list.Count(); //in this case countItems=1
An array, which you start with, is IEnumerable<T>. IEnumerable<T> has a Distinct() method which can be used to manipulate the list into its distinct values
var distinctList = list.Distinct();
Finally,IEnumerable<T> has a ToArray() method:
var b = distinctList.ToArray();
I think using c# Dictionary is the better way and I can sort by value using LINQ
The short story: I want to convert a list/dictionary into an anonymous object
Basically what I had before was:
var model = from item in IEnumerable<Item>
select new
{
name = item.Name
value = item.Value
}
etc.
If I have name, item.Name in a list or dictionary, how can I go about creating the same anonymous object model?
Edit: Clarification:
If the dictionary contains [name, item.Name] and [value, item.Value] as Key Value pairs, how would I go about creating the model without assuming that you know neither name nor value?
Since a List<T> implements IEnumerable<T> your existing code should work exactly the same way:
var model = from item in yourList
select new { name = item.Name };
For a Dictionary<TKey,TValue> you could simply do this:
var model = from item in yourDictionary
select new {
name = item.Key
value = item.Value
};
This works because Dictionary<TKey,TValue> implements IEnumerable<KeyValuePair<TKey,TValue>> so in the second expression item will be typed as KeyValuePair<TKey,TValue> which means you can project a new type using item.Key and item.Value.
It sounds like you just want to get the values from a dictionary? If so, MyDictionary.Values should do the trick for you.
If you want to construct, somewhere else, another anonymous object, that is type-compatible with the one you generate from your IEnumerable<Item>, you can do that by ensuring that the anonymous type you construct has:
The same number of members
Members with the same type
Members with the same name
... in the same order
If you do that, they will map to the same single generated type.
Now, why you would want to do that is beyond me, so I'm pretty sure I didn't understand your question. You should post more information about what you want to do.
Anyway, here's the code to produce an anonymous object that is type-compatible with the one from your IEnumerable:
var x = new
{
name = dict["name"],
value = dict["value"]
};
Since this obeys all the rules above, it will be of the same type as your objects generated from your Linq query.