Select Multiple Fields from List in Linq
Anonymous types allow you to select arbitrary fields into data structures that are strongly typed later on in your code:
var cats = listObject
.Select(i => new { i.category_id, i.category_name })
.Distinct()
.OrderByDescending(i => i.category_name)
.ToArray();
Since you (apparently) need to store it for later use, you could use the GroupBy operator:
Data[] cats = listObject
.GroupBy(i => new { i.category_id, i.category_name })
.OrderByDescending(g => g.Key.category_name)
.Select(g => g.First())
.ToArray();
Linq Syntax - Selecting multiple columns
As the other answers have indicated, you need to use an anonymous type.
As far as syntax is concerned, I personally far prefer method chaining. The method chaining equivalent would be:-
var employee = _db.EMPLOYEEs
.Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
.Select(x => new { x.EMAIL, x.ID });
AFAIK, the declarative LINQ syntax is converted to a method call chain similar to this when it is compiled.
UPDATE
If you want the entire object, then you just have to omit the call to Select()
, i.e.
var employee = _db.EMPLOYEEs
.Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo);
C# LINQ Select table from list with multiple fields
You get a compiler error when using selectedItems.Texture
because selectedItem
is a list that contains an object with the Texture
property. You need to check all of the items in the list when searching for the desired items in FabricTable
:
var items = db.FabricTable.Where(o => selectedItems.Any(selectedItem => o.Texture == selectedItem.Texture && o.Year == selectedItem.Year));
How to Select Multiple Fields from DataGridView using LINQ in C# WinForms
Think I can translate this one:
//all pages hits and the IPs hitting them report
select page, ip, count(page)
from [LogFileName]
group by page, ip
order by count(page) desc
as
var pageCountQuery = (dataGridViewIISDateTime.Rows.Cast<DataGridViewRow>()
.Where(r => r.Cells[9].Value != null && r.Cells[5].Value != null)
.Select(r => new { Page = r.Cells[9].Value, IP = r.Cells[5].Value })
.GroupBy(pageip => pageip)
.OrderByDescending(g => g.Count())
.Select(g => new { PAGE = g.Key.Page, IP = g.Key.IP, HITS = g.Count() })).ToList();
You haven't said what column HTTP code is in.. But the second SQL you've posted has syntax errors and would only really work in MySQL, and even then only if ONLY_FULL_GROUP_BY is deactivated
Select multiple columns with linq to sql
You current request will query the whole user (select *).
In most cases, it is enough and you can access to each column separately :
var user = mycontext.Users.SingleorDefault(p => p.UserId == 1);
var userName = user.Username;
var password = user.Password;
// etc...
If you only need one (or several columns) but not the whole user, you can do it like this:
var userInfo = mycontext.Users.Where(p => p.UserId == 1).Select(p => new {p.UserName, p.Password}).SingleOrDefault();
var userName = userInfo.UserName;
var password = userInfo.Password;
If you prefer a collection of string in result, you can do it this way:
List<string> userInfo = mycontext.Users.Where(p => p.UserId == 1).Select(p => new List<string> { p.UserName, p.Password }).SingleOrDefault();
var username = userInfo[0];
var password = userInfo[1];
This way, the generated query will looks like Select UserName, Password From UserTable
. Its usefull only if your table has a lots of columns or a heavy one (blob for example).
How it works: by calling the Where
extension methods firstly, you tell .NET to not run the query immediately. It will be executed on the SingleOrDefault
call. But at this moment, the query has been completed and the whole part is done in SQL.
query collection for multiple fields with Linq
Add a Select
clause to return the Tuple
. Also Any
is used to validate if video tags contains the search term for TagName.
videos = videos.Where(v => v.Name.Contains(searchTerm) ||
v.Description.Contains(searchTerm) ||
v.VideoTags.Any(t => t.Tag.TagName.Contains(searchTerm)))
.Select(v => new Tuple<string, string, string>(v.Name, v.Description, v.VideoTags.FirstOrDefault(t => t.Tag.TagName.Contains(searchTerm))));
The VideoTags
is not a collection so you can Check the search term in TagName
by accessing the property directly.
Select multiple columns from Linq query
You wrote:
CUstomerBenefits - CustomerID, BenefitID (Both IDs have a relation to
their relevant tables)
I interpret this as meaning that there is a table CustomerBenefit
that contains, well, benefits and that the CUstomerBenefits
table in turn is a link between the customer and the benefits. And now you want to get a list of all the benefits that a specific customer has?
This should do the trick:
IEnumerable<CustomerBenefit> GetData =
from c in MyContext.CUstomerBenefits
where c.CustomerId == UserId && c.Active == true
orderby c.CustomerBenefit.BenType descending
select c.CustomerBenefit;
Linq for filtering data into object with multiple fields, one of them being List<string>
I hope I understood your intension correctly. Now assuming that Value2 would not change when id changes (since you haven't mentioned how to handle such a scenario), you could do the following,
public class RetType{
public int id {get; set;}
public string Value1 {get; set;}
public string Value2 {get; set;}
public List<string> Value3 {get; set;}
}
var finalResult = result.GroupBy(x=>x.Id)
.Select(x=> new RetType
{
id = x.First().Id,
Value2 = x.First().Value2,
Value3 = x.Select(c=>c.Value3).ToList()
})
Do note that in your RetType
you have used List<string>
to represent the Value3. If you need to have it as comma separated string (as in the table in OP), you could use a string.Join
var finalResult = result.GroupBy(x=>x.Id)
.Select(x=> new RetType
{
id = x.First().Id,
Value2 = x.First().Value2,
Value3 = string.Join(",",x.Select(c=>c.Value3))
})
Where the RetType is defined as
public class RetType{
public int id {get; set;}
public string Value1 {get; set;}
public string Value2 {get; set;}
public string Value3 {get; set;}
}
Related Topics
The Ssl Connection Could Not Be Established
How to Secure the Asp.Net_Sessionid Cookie
Access Variables/Functions from Another Component
How to Delete Records Between Two Dates in Bulk
How to Convert Json Date to .Net Datetime During Deserialization
Asp.Net Core Form Post Results in a Http 415 Unsupported Media Type Response
Replace Single Backslash With Double Backslash
How to Prevent the Print Progress Dialog Appearing When Performing a Print Preview
What Regular Expression Would I Use to Remove Everything After the Second Backslash
Sorting a Collection Containing Strings And/Or Numbers
C# Windows Form Application for Employee Management
How to Determine If .Net Core Is Installed
How to Programmatically Set the System Volume
Download File from an ASP.NET Web API Method Using Angularjs
Configurationmanager.Appsettings Getting Null
Where Is the Postasjsonasync Method in ASP.NET Core