Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double select in list

Tags:

c#

.net

linq

How can i select name in list? which is itself in list???

My struct:

public class Item
{
    int id;
    List<Name> names;
}

public class Name
{
    int id; 
    string name;
}

List<Item> Items;

code:

Items.Select(a => a.id = 1) //whats next 
like image 876
Alex F Avatar asked Jun 02 '26 04:06

Alex F


2 Answers

Assuming you want all of the names in a list, you can do:

List<Name> matchingNames = Items.Where(a => a.id == 1).Select(a => a.names);


Or if you want a list of the string names from the list, you can do:

List<string> matchingNames = Items
    .Where(a => a.id == 1)
    .SelectMany(n => n.names)
    .Select(n => n.name)
    .ToList();

Then, if you're using my second statement, you can output a list in the format item, item, item by doing:

string outputtedNames = string.Join(", " + matchingNames);

EDIT: As requested in comments, here's how you can get names by ID based on the Name ID:

List<Name> matchingNames = Items
    .SelectMany(a => a.names)
    .Where(n => n.id == 1)
    .ToList();

EDIT 2: To display name items and items that both have an ID of 1, try this:

List<Name> matchingNames = Items
    .Where(a => a.id == 1)
    .SelectMany(a => a.names)
    .Where(n => n.id == 1)
    .ToList();
like image 142
mattytommo Avatar answered Jun 03 '26 17:06

mattytommo


you can use

var result = Items.Where(a => a.id == 1 && a.names.Contains(333)).Select(a => a.names);
like image 43
Aghilas Yakoub Avatar answered Jun 03 '26 18:06

Aghilas Yakoub