I am writing the following line of code to extract the selected items in checklistbox.
ListItemCollection ChecklistBoxCollection = new ListItemCollection();
foreach (ListItem ChecklistBoxItem in ChecklistBox.Items)
if (ChecklistBox.Selected)
ChecklistCollection.Add(ChecklistBox);
Is there any way to get these items in LinQ?
There's no automatic conversion to ListItemCollection, but you can use AddRange to add the selected items at once. I'm not sure this is much of an improvement and may be slower because AddRange only takes an array.
ListItemCollection ChecklistBoxCollection = new ListItemCollection();
ChecklistBoxCollection.AddRange( checklistBox.Items
.Cast<ListItem>()
.Where( i => i.Selected )
.ToArray() );
I have been using these extension methods.
public static List<string> GetCheckedValues(this CheckBoxList list)
{
var values = new List<string>();
values.AddRange(from ListItem item in list.Items
where item.Selected
select item.Value);
return values;
}
public static List<string> GetCheckedTexts(this CheckBoxList list)
{
var values = new List<string>();
values.AddRange(from ListItem item in list.Items
where item.Selected
select item.Text);
return values;
}
Related
***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++;
}
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();
My Code:
ObservableCollection<SampleCheckedData> interestrates = new ObservableCollection<SampleCheckedData>();
XDocument xmlDocu = XDocument.Load(new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(result)));
interestrates = (from rts in xmlDocu.Descendants("Friend")
select new SampleCheckedData
{
Id = (string)rts.Element("userid"),
Name = (string)rts.Element("name"),
Icon = (string)rts.Element("imageurl"),
VisibleStatus = (string)rts.Element("visiblestatus"),
AppStatus = (string)rts.Element("loginstatus"),
imgBubble =bitmapRed,
}).ToList<SampleCheckedData>();
Then Getting Error as can't implicitly convert system.collection.generic.list to system.collection.observablecollection like that.How to bind listbox items using observable collection?
EDIT:
Button b = sender as Button;
var res = interestrates.Where(a => a.Id.Equals(((System.Windows.FrameworkElement)(e.OriginalSource)).Tag)).ToList();
if (res.Count == 1)
interestrates.Remove(res.First());
interestrates = new ObservableCollection<SampleCheckedData>();
lstFriendRequuest.ItemsSource = "";
bindGetFriends();
Here successfully deleting item from list but after calling bindGetFriends() in that binding the items newly then i am not getting new items getting old items.why the service returning old items list?
Use this extension:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public static class Extensions
{
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> collection)
{
var observableCollection = new ObservableCollection<T>();
foreach (var item in collection) observableCollection.Add(item);
return observableCollection;
}
}
Usage:
interestrates = (from rts in xmlDocu.Descendants("Friend")
select new SampleCheckedData
{
Id = (string)rts.Element("userid"),
Name = (string)rts.Element("name"),
Icon = (string)rts.Element("imageurl"),
VisibleStatus = (string)rts.Element("visiblestatus"),
AppStatus = (string)rts.Element("loginstatus"),
imgBubble =bitmapRed,
}).ToObservableCollection<SampleCheckedData>();
Change your Observable collection to List,
List<SampleCheckedData> interestrates = new List<SampleCheckedData>();
You can also bind List to ListBox, instead of ObservableCollection
And to solve your other problem of deleting selected item from listbox, try the following code:
var selectedIndex = listbox.SelectedIndex;
var listItems = listbox.ItemsSource as List<SampleCheckedData>;
listItems.RemoveAt(selectedIndex);
listbox.ItemsSource = null;
listbox.ItemsSource = listItems;
If still you are facing problems, let me know
I have a dataset table, I want to group it by column MOID, and then within this group I want to select the row which has max value of column radi.
Can anybody show me how to do it via LINQ to dataset?
Although the solution posted by Barry should work (with a few fixes), it is sub-optimal : you don't need to sort a collection to find the item with the maximum value of a field. I wrote a WithMax extension method, which returns the item with the maximum value of the specified function :
public static T WithMax<T, TValue>(this IEnumerable<T> source, Func<T, TValue> selector)
{
var max = default(TValue);
var withMax = default(T);
bool first = true;
var comparer = Comparer<TValue>.Default;
foreach (var item in source)
{
var value = selector(item);
int compare = comparer.Compare(value, max);
if (compare > 0 || first)
{
max = value;
withMax = item;
}
first = false;
}
return withMax;
}
It iterates the collection only once, which is much faster than sorting it just to get the first item.
You can then use it as follows
var query =
from row in table.AsEnumerable()
group row by row.Field<int>("MOID") into g
select g.WithMax(r => r.Field<int>("radi"));
This is untested but I think something like this should work:
var qry = from m in [YourDataSource]
group p by m.MOID into grp
select grp.OrderByDescending(a => a.RADI).First();
this works with one query!
public static T WithMax<T, TValue>(this IEnumerable<T> source, Func<T, TValue> keySelector)
{
return source.OrderByDescending(keySelector).FirstOrDefault();
}
I'm iterating the tables of a context and then the properties of those tables to eager load all columns in a context. I received some help via another question, but I don't seem to be able to figure out how to iterate the column properties of the actual table.
Final working code:
public static void DisableLazyLoading(this DataContext context)
{
DataLoadOptions options = new DataLoadOptions();
var contextTables = context.GetType().GetProperties().Where(n => n.PropertyType.Name == "Table`1");
foreach (var contextTable in contextTables)
{
var tableType = contextTable.GetValue(context, null).GetType().GetGenericArguments()[0];
var tableProperties = tableType.GetProperties().Where(n => n.PropertyType.Name != "EntitySet`1");
foreach (var tableProperty in tableProperties)
{
ParameterExpression paramExp = Expression.Parameter(tableType, "s");
Expression expr = Expression.Property(paramExp, tableProperty.Name);
options.LoadWith(Expression.Lambda(expr, paramExp));
}
}
context.LoadOptions = options;
}
You're only getting the ProperInfos. You need to get the values from the PropertyInfos:
var tablePropertInfos = context.GetType().GetProperties().Where(
n => n.PropertyType.Name == "Table`1");
foreach (var tablePropertyInfo in tablePropertInfos)
{
// Get the actual table
var table = tablePropertyInfo.GetValue(context, null);
// Do the same for the actual table properties
}
Once you have the PropertyInfo class, you need to get the value using the GetValue method.