How to combine two columns from a database with LINQ? - c#

// Appetizers Filter
var Appetizers =
from a in this.restaurantMenuDataSet.Menu
where a.Category == "Appetizer"
select a;
foreach (var a in Appetizers) AppCombo.Items.Add(a.ItemName);
So with this I get appetizers from an access database, but I also want to display its price along side it in ComboList. So basically I want the list to show "Nachos $5.95"
Database:
ComboList:

You can use String.Format to combine ItemName and Price in order to display in combobox:
foreach (var a in Appetizers)
{
var displayName = String.Format("{0} {1}", a.ItemName,a.Price);
AppCombo.Items.Add(displayName);
}

Related

Updating List<string> values using linq C#

I have a list of strings that I would like to iterate through and change the values if certain items in the list if they match up to a string value in a separate list of objects.
User inputs an email address into an Event object that contains a list of EventMembers:
List<string> EventMembers
I would then like to check through all users in the database to find the username(e-mail address) that matches with the inputted e-mail address
i understand I cannot change values in a list using a foreach loop, but i'm lost with what to do with linq. Basically i'm trying to do something like this:
var allUsers = _userManager.Users
foreach (var a in allUsers)
{
foreach (var e in #event.EventMembers)
{
if (e == a.UserName)
{
e = a.FirstName + a.LastName;
}
}
}
The best thing would be to define an initial collection of members so you don't keep modifying the list while the foreach is still running. You could then check if EventMembers contain the username and then replace it by accessing the value with the index.
var allUsers = _userManager.Users;
List<string> Members;
foreach (var a in allUsers)
{
if (#event.EventMembers.Contains(a.UserName))
{
var index = #event.Members.IndexOf(a.UserName);
Members[index] = a.FirstName + a.LastName;
}
}
EventMembers = Members;

Getting values from deleted rows in data grids using winforms

I am using typed datasets with datagrids. When I delete a row I use the dataset.HasChanges filter and get changes as follows.
dtDel = (Database1DataSet1.product_skuDataTable)database1DataSet1.product_sku.GetChanges(DataRowState.Deleted);
I am trying to get values(Product Names) from deleted rows as follows.
private string getProdNames(DataTable dtDel)
{
string prodNames = "";
var q = dtDel.AsEnumerable().Select(x => x.Field<string>("ProductName"));
foreach (string p in q)
{
prodNames += p + "\n";
}
return prodNames;
}
But I am getting the following error.
Deleted row information cannot be accessed through the row.
Thanks
Found the answer here and here
The linq query will work like this
var q = dt.AsEnumerable().Select(x => x.Field<string>(colName, DataRowVersion.Original));

Get first and last column value in C#

I am using the following code in my .NET web service that gets its data form a CSV file.
private List<Item> ietms = new List<Item>();
public ItemRepository()
{
string filename = HttpRuntime.AppDomainAppPath + "App_Data\\items.csv";
var lines = File.ReadAllLines(filename).Skip(1).ToList();
for (int i = 0; i < lines.Count; i++)
{
var line = lines[i];
var columns = line.Split('$');
//get rid of newline characters in the middle of data lines
while (columns.Length < 9)
{
i += 1;
line = line.Replace("\n", " ") + lines[i];
columns = line.Split('$');
}
//Remove Starting and Trailing open quotes from fields
columns = columns.Select(c => { if (string.IsNullOrEmpty(c) == false) { return c.Substring(1, c.Length - 2); } return string.Empty; }).ToArray();
var temp = columns[5].Split('|', '>');
items.Add(new Item()
{
Id = int.Parse(columns[0]),
Name = columns[1],
Description = columns[2],
Category = temp[0]
});
}
}
This code gets a list of products from the CSV file along with its name, description etc. Each product belongs to either one or two categories : Category = temp[0].
Each product's category is found in a column of the csv file with it's data structured as such:
Groups>Subgroup>item, in which case, this product belongs to category "Groups".
The category column of a product may also be structured as:
MajorGroup|Groups>Subgroup>item, in which case this product belongs to category "MajorGroup".
Also, in many cases a product's category column may be structured as:
MajorGroup|Groups>Subgroup>item|SecondGroup, in which case this product belong to both the categories "MajorGroup" and "SecondGroup"
The code above that I am currently using does half the job. If a product has a category defined in the CSV file as MajorGroup|Groups>Subgroup>item|SecondGroup, it assigns it to category "MajorGroups" but not "SecondGroup".
This line var temp = columns[5].Split('|', '>'); gets the first value structured taht way and separated by a pipe and sets it as the product's category here Category = temp[0].
How do I fix this so that if the category is structured as MajorGroup|Groups>Subgroup>item|SecondGroup, with two categories, then it will show up in both categories.
How do I assign the product to one or more categories depending on the structure of the category column data.
This works for the most part, but how do I alter the code to check and assign for both categories?
Can I change this var temp = columns[5].Split('|', '>'); to get both teh first and the last value if it exists and assign both to Category = temp[0].
To get the second group values given the problem statement as specified you could do the following.
...
var temp = columns[5].Split('|', '>');
string categories= temp[0];
if (input.Count(x => x == '|') >= 2)
{
categories+= "," + temp.Last();
}
...
Category = categories;
Then one could get a list of Items that is assigned to a category by the following function:
static public IList<Item> GetProductsByCategory(string category, IList<Item> items)
{
return items.Where(x => x.Category.Split(',').Contains(category,StringComparer.OrdinalIgnoreCase)).ToList();
}
A much cleaner solution is to store the categories within the Item class as something that implements ILIST.
You should definitely use some CSV parser instead of doing this manually. There are too many potential problems and issues when parsing CSV manually that it is much easier and faster to use some existing tool like:
FileHelpers
Fast CSV Reader

how to bind one dimensional string array result to datagrid column header

I have a query as follows, which returns the list of server names and component names
string match = "TEST"
var headerArray = from a in this.db.Servers
where a.ServerID.Contains(match)
join b in this.db.Components
on a.ServerID equals b.ServerID into g
select new
{
a.ServerID,
Components = g.Select(x => x.Name),
};
List<string> result = new List<string>();
foreach (var server in headerArray)
{
result.Add(server.ServerID);
foreach (var componentName in server.Components)
result.Add(componentName);
}
string[] header = result.ToArray();
EDIT
datagrid1.ItemsSource = header.ToList();
header stores the list of servernames in the form of array. how to bind this result to the datagrid column ?
You can not bind gridview header columns.
You need to create a loop with string[] header and add columns dynamically.
you can go through the below url for how to add columns dynamically in gridview
How to add a GridView Column on code-behind?
http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view

How to get only specific field from the list

I have an IEnumerable of Lesson objects:
IEnumerable<Lesson> filteredLessons
I convert it to a List through the following method:
ToList();
But I want the returned list to contain only the first property, lessonid, not all the Lesson properties.
How can I get the data of specific property of the list instead of the objects?
You can select the value you want first, like this:
filteredLessons.Select(l => l.lessonId).ToList();
And you'll get a list of ID's
If you want to get the the specific row value from list using linq use the following code:
var name = from r in objClientList
where r.ClientCode == Convert.ToInt32(drpClientsInternal.Items[i].Value)
select r.IsInternalClient;
foreach (bool c in name)
{
if (c)
{
ClientNameInternal = ClientNameInternal + drpClientsInternal.Items[i].Text +", ";
drpClientsInternal.Items[i].Selected = true;
}
}

Categories