score:2
It sounds like you really just want to build up a Lookup from country to servers:
var lookup = servers.ToLookup(server => server.Country);
If that's not what you're looking for, please let me know how it doesn't do what you want :)
Admittedly there's no guarantee that each Country
will have all the servers in the original list, and that sounds like it's that distinction which is really the problem.
If your Server
already has the Country
set, can you not assume that the data is already consistent? If not, shouldn't your Server
really have a CID instead of a Country
reference? Having a property which will sometimes be consistent with "this" object and sometimes not (i.e. whether server.Country.Contains(server)
is guaranteed to return true
or not) is ugly IMO.
EDIT: Okay, a possibly nicer alternative is:
var query = servers.GroupBy(server => server.Country.CID);
.Select(g => new Country { CID = g.Key,
Servers = g.ToList() });
This is almost the same as fermaref's approach, but I'm explicitly using Country.CID
to avoid two servers with equivalent countries not ending up in the same bucket due to potentially odd equality rules.
score:1
Now I have a list of servers with each country set and want to group by country so I can set the opposite list.
Linq is for querying and it has a functional mindset where you generate new instances instead of modifying existing instances.
If you want to modify instances, a foreach loop is superior:
List<Server> servers = GetServers();
foreach(Server server in servers)
{
Country c = server.Country;
c.Servers.Add(server);
}
If you must use Linq:
List<Server> servers = GetServers();
foreach(IGrouping<Country, Server> g in servers.GroupBy(s => s.Country))
{
Country c = g.Key;
c.Servers = g.ToList();
}
Now I just need to invert the list.
ILookup<Country, Server> lookup = servers.ToLookup(s => s.Country);
List<Country> countries = lookup.Select(g => g.Key).ToList();
foreach(Country c in countries)
{
c.Servers = lookup[c].ToList();
}
return countries;
score:0
If you can't guarantee that the Country
object in each Server
object already contains all the Servers, you can create a new Country
object:
var groupBy = list.GroupBy(
x => x.Country,
x => x, (c, s) =>
new Country
{
CID = c.CID,
Servers = s.ToList()});
However, I'm not sure if that's what you want.
If you can guarantee that the Country
object will always contain all Servers
, you can could use the following:
var countries = list.SelectMany(s => s.Country).Distinct();
or, if your Country
doesn't implement IEquateable
:
var groupBy = list.GroupBy(x => x.Country).Select(x => x.Key);
Source: stackoverflow.com
Related Articles
- C# LINQ GroupBy to convert a List to a group with one property as List of values
- c# Linq or code to extract groups from a single list of source data
- Convert string[] to int[] in one line of code using LINQ
- Convert list to dictionary using linq and not worrying about duplicates
- LINQ - Convert List to Dictionary with Value as List
- Convert dictionary values to list using linq
- Using LINQ to convert a list to a CSV string
- Convert CollectionBase to List or data type usable with Linq
- C# LINQ - convert nested dictionary to a list
- Convert a list to a dictionary and sum up values using linq
- LINQ with subselect and groupby to get only the latest version of each item in a list
- Convert string array to custom object list using linq
- convert comma separated string to list using linq
- c# linq GroupBy on the values of a List within a List
- Convert LINQ orderby to inplace list sort
- LINQ Source Code Available
- How to convert list of objects with two fields to array with one of them using LINQ
- Use LINQ to Convert a List to a List of Lists
- Cannot convert source type to target type List<KeyValuePair> Linq
- How to Convert Anonymous Type to List <dynamic> using Linq to SQL in C#
- Groupby list within the list using LINQ
- Linq to Xml Convert a list
- LINQ Lambda efficiency of code groupby orderby
- Cannot implicitly convert linq result into viewmodel list
- LINQ GroupBy return List as result
- How can i convert Linq var to List
- LINQ query returns old results when source list is re-initialized
- C# - Linq optimize code with List and Where clause
- convert foreach loop to linq code
- Split one list into many by month - C#, Linq
- C# set datasource for combobox in datagridview
- A List of Field Names as a String Array - LINQ Expressions
- Null result in LINQ vb.net
- Get data from SQL Server using linq
- IQueryable remove from the collection, best way?
- What is the big deal with IQueryable?
- How does one Left Outer Join on multiple OR columns? C# & Entity Framework
- LINQ OrderBy / ThenBy with conditional sorting
- Best practice to merge Table Entity with View Entity
- Entity Framework Select with Include + Group By Count + Paging and Projection
- How to create AutoMap feature for FluentNHibernate based on attributes?
- Selecting XML nodes using LINQ
- Linq receiving unable to create value type of model, only primitive types or enumeration types are supported
- any free linq provider available for oracle?
- Performing a LINQ search on all properties of a list of entities without duplicates
- Sorting data in Linq query
- C# Linq spare a double foreach
- How can i get element in string by Linq
- Retrieving 10 records at a time only using LINQ
- get a List of Max values across a list of lists