how to convert var to dictionary and access var using foreach loop - linq

i have a dictionary defined as follows:
Dictionary<string, int> Controls = new Dictionary<string, int>();
using the following code i am putting keys which have similar value into var
var result = (from p in Controls
group p by p.Value into g
where g.Count() > 1
select g);
But neither i am able to convert 'result' into dictionary again or nor i am able to access item inside 'result'
i tried this code but
foreach (System.Linq.Lookup<int, KeyValuePair<string, int>> Item in result)
{
}
Plz help.

try this:
var dict = result.ToDictionary(x => x.Key, x => x.Select(y => y.Key).ToList())
and access it like
foreach(var item in dict)
BTW, there's no type var. It's just instruction for the compiler to determine type for variable, but it's strongly typed. In your case, I think, it would be IEnumerable<IGrouping<TKey, TSource>>. Actually you can access result like this too:
foreach(var item in result)
{
// item is type Lookup<int, KeyValuePair<string, int>>.Grouping
// you can go through item like
foreach(var i in item)
{
}
// or convert it ToList()
var l = item.ToList()
// l is type List<KeyValuePair<string, int>>
}

Related

Load multipe sharepoint list item fields in one Go using CSOM c#

***ctx.Load(listItemCollection,
eachItem => eachItem.Include(
item => item,
item => item["Column1"],
item => item["Column2"]
));***
i have list of fields in a array of string instead of column1 and column2, how can i pass it through in include linq, not able to create proper lambda on runtime. i tried following ways but couldn't get success. Static befor loops works but thw fields added in loop fails as it doesn't evaluate string value in loop
***Expression<Func<ListItem, object>>[] paramss = new
Expression<Func<ListItem, object>>[length];
paramss[0] = x => x.ContentType;
paramss[1] = x => x["Title"];
count = 2;
foreach (string item in solConnDefModel.Columns)
{ paramss[count] = x => x[item];
count++;
}***
Please take a reference of below code:
List dlist = context.Web.Lists.GetByTitle("listname");
context.Load(dlist);
context.ExecuteQuery();
string[] fieldNames = { "Id", "Title", "num", "mStartDate" };
// Create the expression used to define the fields to be included
List<Expression<Func<ListItemCollection, object>>> fieldsToBeIncluded = new List<Expression<Func<ListItemCollection, object>>>();
foreach (string s in fieldNames)
{
fieldsToBeIncluded.Add(items => items.Include(item => item[s]));
}
// Initialize the collection of list items
var listItems = dlist.GetItems(new CamlQuery());
context.Load(listItems, fieldsToBeIncluded.ToArray());
context.ExecuteQuery();
You can hover on load method to see what type parameter it requires, then generate a corresponding one and pass it.
i have to create lambda expression at runtime. following code i was able to get expected value
Expression<Func<ListItem, object>>[] paramss = new Expression<Func<ListItem, object>>[length];
foreach (string item in Columns)
{
if (item.ToLower() != "contenttype")
{
ParameterExpression parameter = Expression.Parameter(typeof(ListItem), "x");
var propertyInfo = typeof(ListItem).GetMethod("get_Item");
var arguments = new List<Expression> { Expression.Constant(item) };
var expression = Expression.Call(parameter, propertyInfo, arguments);
var lambda = Expression.Lambda<Func<ListItem, object>>(expression, parameter);
paramss[count] = lambda;
}
else
{
paramss[count] = x => x.ContentType;
}
count++;
}

Dictionary<string, List<Dictionary<string,string>>> query using linq

I have the below dictionary
Dictionary<string,string> q1=new Dictionary<string,string>
{
{"h1","name1"},{"h2","name2"}
};
Dictionary<string,string> q2=new Dictionary<string,string>
{
{"h1","name12"},{"h2","name23"}
};
Dictionary<string,string> q3=new Dictionary<string,string>
{
{"h1","name123"},{"h2","name234"}
};
List<Dictionary<string,string>> m1 = new List<Dictionary<string,string>> { q1,q2,q3 };
Dictionary<string, List<Dictionary<string,string>>> mhi = new Dictionary<string, List<Dictionary<string,string>>>();
mhi.Add("x1", m1);
I need to return a list which has the values name1,name12,name123 using linq.
I am aware of normal method which works for me. But I am curious to know how to implement this using linq
Try this:
var q1 = new Dictionary<string, string> {
{"h1", "name1"},
{"h2", "name2"}
};
var q2 = new Dictionary<string, string> {
{"h1", "name12"},
{"h2", "name23"}
};
var q3 = new Dictionary<string, string> {
{"h1", "name123"},
{"h2", "name234"}
};
var m1 = new List<Dictionary<string, string>> { q1, q2, q3 };
//Using LINQ
List<string> result = (from dictionary in m1
from keyValuePair in dictionary
where keyValuePair.Key == "h1"
select keyValuePair.Value).ToList();
//result = name1,name12,name123
//without linq
var result2 = new List<string>();
foreach(var dictionary in m1)
foreach(var keyValuePair in dictionary)
if(keyValuePair.Key == "h1")
result2.Add(keyValuePair.Value);
Edit:
The from clause specifies the data source, the where clause applies the filter, and the select clause projects each element of the sequence into a new form.
Linq queries are not executed until we iterate through it. (Here .ToList() is doing that). It's like a blueprint which specifies how the information is returned when executed(iterated).
Lets examine each statement separately:
from dictionary in m1 - This is much like foreach(var dictionary in m) except that it doesn't iterate (Because its a blueprint). It specifies which source we are iterating through (m1) and the variable to assign to each member (dictionary that is. We know that it will be of type Dictionary<String, String>)
from keyValuePair in dictionary - Here we use the dictionary variable created from the previous statement. The type of keyValuePair will be KeyValuePair<string,string> because we will be "iterating" through a Dictionary<string,string> when the query is executed.
where keyvaluePair.Key == "h1" - This filters out the keyValuePairs from the previous statement whose Key property equals "h1".
Now that we filtered out the KeyValuePairs, we can select their Value property. This "projects" the filtered out KeyValuePair sequence to the new type IEnumerable<string>
Finally, ToList method executes the query to get the results.

LINQ with list<int> quering the Value of a Dictonary<int, object>

I have a problem with a query. I have a List with int and want to use it to get the values from my dictionary. The dictionary-keys are int and some of them have the value of the list-items. My question is how i get the objects out of the dictionary, thats keys matces the list items. Was programming JAVA the last years and now struggling with LINQ :(
Thanks in advance
Problem solved. Thank you all :)
No idea how to close this topic. I am reading stackoverflow since one year, but this was my first post.
You can use Linq to join list items with dictionary KeyValuePair entries on entry key. And then select entry value from each joined pair:
var values = from l in list
join kvp in dictionary on l equals kvp.Key
select kvp.Value;
Lambda syntax:
var values = list.Join(dictionary, l => l, kvp => kvp.Key, (l,kvp) => kvp.Value);
Basically:
var value = dictionary[integerKey];
Or:
if (dictionary.TryGetValue(integerKey, out value)) {
}
You can also create an extension method:
public static class DictionaryExtensions
{
public static IEnumerable<TValue> FilterValuesBy<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IEnumerable<TKey> filter)
{
if (dictionary == null) throw new ArgumentNullException("dictionary");
if (filter == null) throw new ArgumentNullException("filter");
var coll = filter as ICollection<TKey> ?? new HashSet<TKey>(filter);
return dictionary.Where(kvp => coll.Contains(kvp.Key)).Select(kvp => kvp.Value);
}
}
Usage:
class Program
{
static void Main()
{
var dict = Enumerable.Range(0, 10).ToDictionary(x => x);
var filter = Enumerable.Range(0, 2);
foreach (var i in dict.FilterValuesBy(filter))
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
Simple Linq method chain:
var dict = Enumerable.Range(0, 10).ToDictionary(x => x);
var filter = Enumerable.Range(0, 2).ToList();
var filtered = dict.Where(x => filter.Contains(x.Key)).Select(x => x.Value).ToList();

linq select from database where ID in an ArrayList

I have an array-list that contains some UserID.
I need a query like this:
vat tmp= users.select(a=> a.UserID in (arraylist));
what can I do?
If it's actually in an ArrayList, you should create a List<T> or array first. Then you can use Contains:
// Use the appropriate type, of course.
var ids = arraylist.Cast<string>().ToList();
var tmp = users.Select(a => ids.Contains(a.UserID));
While using Contains on the plain ArrayList may well compile, I would expect it to fail at execution time, assuming users is an IQueryable<>.
List<long> list =new List<long>();
var selected = from n in users where list.Contains(n.ID) select n ;
OR
var selected = users.Where(a=> list.Contains(a.ID)).ToList();
This is the solution I used.
public static IEnumerable<SettingModel> GetSettingBySettingKeys(params string[] settingKey)
{
using (var db = new BoxCoreModelEntities())
{
foreach (var key in settingKey)
{
var key1 = key;
yield return Map(db.Settings.Where(s => s.SettingKey == key1).First());
}
}
}

LINQ: IEnumerable<KeyValuePair<SomeType, IEnumerable<OtherType>>> selection

How do I transform this IEnumerable<KeyValuePair<MyType, IEnumerable<OtherType>>> into new
sequence of the same type, except I just want First() that is in the value (IEnumerable<OtherType>). Something like this (pseudo code):
var toReturn = from kv in source
let k = new KeyValuePair(kv.Key, kv.Value.First())
select k;
I'm unsure if you want the Value in the new KeyValuePair to be an enumerable of that type or a single element. Here's both versions
IEnumerable version
var toReturn = source.Select(x => new KeyValuePair<SomeType,IEnumerable<SomeOtherType>>(x.Key, x.Value.Take(1));
Non-Enumerable Version
var toReturn = source.Select(x => new KeyValuePair<SomeType,SomeOtherType>(x.Key,x.Value.First());
All you're missing is the type of KeyValuePair to use. You could use Jared's lambda expression version, or if you like the query expression syntax:
var toReturn = from kv in source
select new KeyValuePair<MyType, OtherType>(kv.Key,
kv.Value.First());
If you don't want to explicitly specify the type arguments, you could create your own helper class and use type inference:
// Non-generic helper class.
public static class KeyValuePair
{
public static KeyValuePair<TKey, TValue> Of(TKey key, TValue value)
{
return new KeyValuePair<TKey, TValue>(key, value);
}
}
at which point your query becomes:
var toReturn = from kv in source
select KeyValuePair.Of(kv.Key, kv.Value.First());
or
var toReturn = source.Select(kv => KeyValuePair.Of(kv.Key, kv.Value.First());
EDIT: Oops - I think I'd misread your question as well. If you want it to be of the exact same type, i.e. with the value being enumerable too, just use Take(1) instead of First():
var toReturn = source.Select(kv => KeyValuePair.Of(kv.Key, kv.Value.Take(1));
(Isn't type inference lovely? :)
var toReturn = source
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Take(1)
);
Why do you want to get a collection of the same type? When you just have the first element, you don't need a collection (IEnumerable<OtherType>) but a single value (OtherType).
This (like the one you posted) should be correct (you will just need to add generic parameters for the KeyValuePair)
var toReturn = from kv in source select new KeyValuePair<SomeType, OtherType>(kv.Key, kv.Value.First());
If you really want to get a collection of the same type, write
var toReturn = from kv in source select new KeyValuePair<SomeType, IEnumerable<OtherType>>(kv.Key, new [] { kv.Value.First() });
Note: You don't need to give explicit type arguments to the KeyValuePair when you wrap this into a generic function.
KeyValuePair<TKey, TValue> Pair<TKey, TValue>(TKey key, TValue value) {
return new KeyValuePair<TKey, TValue>(key, value);
}
//
var foo = Pair(1, "Hello");

Resources