score:29
I think frenchie wants a list of MyModel
back instead of just the TheUniqueID
.
You need to create a MyModelTheUniqueIDComparer
class and pass a new instance of it as a second argument into Union
:
class MyModelTheUniqueIDComparer : IEqualityComparer<MyModel>
{
public bool Equals(MyModel x, MyModel y)
{
return x.TheUniqueID == y.TheUniqueID;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(MyModel myModel)
{
return myModel.TheUniqueID.GetHashCode();
}
}
Then you can call to get the result:
var result = q1.Union(q2, new MyModelTheUniqueIDComparer());
See http://msdn.microsoft.com/en-us/library/bb358407.aspx for a more details.
Update:
Try this:
public class A
{
public string TheData1 { get; set; }
public string TheData2 { get; set; }
public string UniqueID { get; set; }
}
public class AComparer : IEqualityComparer<A>
{
#region IEqualityComparer<A> Members
public bool Equals(A x, A y)
{
return x.UniqueID == y.UniqueID;
}
public int GetHashCode(A obj)
{
return obj.UniqueID.GetHashCode();
}
#endregion
}
And test with this:
var listOfA = new List<A>();
var q1 = from a in listOfA
select new A()
{
TheData1 = "TestData",
TheData2 = "TestData",
UniqueID = a.UniqueID
};
var anotherListOfA = new List<A>();
var q2 = from a in anotherListOfA
select new A()
{
TheData1 = "TestData",
TheData2 = "TestData",
UniqueID = a.UniqueID
};
q1.Union(q2, new AComparer());
Make sure you have using System.Linq;
score:4
Inefficient single line answer with no IEqualityComparerer
Using MoreLinq source code as inspiration, this will give a unique list:
Short answer (the OrderBy isn't necessary but if not used the answer comes out as 2,3,6,9,11,4,7,12):
var concattedUniqueList = theUniqueIDList1.Concat(theUniqueIDList2)
.GroupBy(f=>f.UniqueID, f=>f).Select(g => g.First()).OrderBy(f=>f.UniqueID);
Complete answer:
//INPUT
//theUniqueIDList1 = 2,3,6,9,11
//theUniqueIDList2 = 2,4,7,9,12
//OUTPUT
//2,3,4,6,7,9,11,12
public class MyModel
{
public string TheData1 { get; set; }
public string TheData2 { get; set; }
public int UniqueID { get; set; }
}
public static void GroupByEx1()
{
// Create a list of Models.
List<MyModel> theUniqueIDList1 =
new List<MyModel>{ new MyModel { TheData1="Barley", UniqueID=2 },
new MyModel { TheData1="Boots", UniqueID=3 },
new MyModel { TheData1="Whiskers", UniqueID=6 },
new MyModel { TheData1="Daisy", UniqueID=9 },
new MyModel { TheData1="Preti", UniqueID=11 } };
List<MyModel> theUniqueIDList2 =
new List<MyModel>{ new MyModel { TheData1="Barley", UniqueID=2 },
new MyModel { TheData1="Henry", UniqueID=4 },
new MyModel { TheData1="Walsh", UniqueID=7 },
new MyModel { TheData1="Daisy", UniqueID=9 },
new MyModel { TheData1="Ugly", UniqueID=12 } };
var concattedUniqueList = theUniqueIDList1.Concat(theUniqueIDList2)
.OrderBy(f=>f.UniqueID).GroupBy(f=>f.UniqueID, f=>f).Select(g => g.First());
foreach (var item in concattedUniqueList)
{
Console.WriteLine("UniqueId: {0}({1})", item.UniqueID, item.TheData1);
}
}
void Main()
{
GroupByEx1();
//2,3,4,6,7,9,11,12
}
Note: compared to using an IEqualityComparer for speed - 10000 times for each 698 ns for Concat 100 ns for IEqualityComparer
developed in LinqPad
score:6
As was pointed out if you are combining the lists with .Union(
) you will have to define uniqueness by using the overload passing an IEqualityComparer for your type.
var result = q1.Union(q2, myEqualityComparer);
otherwise, and easier you could use DistinctBy( x=> x.TheUniqueId)
from the MoreLinq project:
var result = q1.Concat(q2).DistinctBy(c => c.TheUniqueID);
score:11
Union
creates an Enumerable with unique values from both collections. In other words, you don't need Distinct
.
edit: example of Union here
edit2: forgot that it's not the list of UniqueIDs
that you're concatenating. I removed the suggested code since it was wrong. You should be able to do a simple Union
if you implement an IEqualityComparer
, but that might be overkill.
Source: stackoverflow.com
Related Query
- LINQ query with Distinct and Union
- LINQ - writing a query with distinct and orderby
- Linq query for a nested select statement with grouping and distinct
- get distinct with min and maximum in linq query
- LINQ query with Distinct and WHERE clause
- C# LINQ Lambda query with select, Where, Count and Distinct
- Selecting multiple columns with linq query and lambda expression
- Using Distinct with LINQ and Objects
- LINQ select query with Anonymous type and user Defined type
- Entity Framework - Linq query with order by and group by
- Linq Query with SUM and ORDER BY
- How to combine 2different IQueryable/List/Collection with same base class? LINQ Union and Covariance issues
- LINQ Query with GROUP and SUM
- Simple sql to Linq query with group by and aggregate functions
- linq distinct and select new query
- Translating query with GROUP BY and COUNT to Linq
- Get excel cell value with Row and Column Position through open xml sdk linq query
- LINQ query with GROUP BY and Count(*) into Anonymous Type
- LinQ query with multiple tables and extracting data
- A LINQ query with grouping and filtering of special groups
- Using LINQ Dynamic Query Library with Dictionary<string, object> and .AsQueryable()
- C# LINQ query (MYSQL EF) - Distinct and Latest Records
- LINQ Union between two tables with the same fields and then returned in a collection
- LINQ - 'Could not translate expression' with previously used and proven query condition
- Optimize/rewrite LINQ query with GROUP BY and COUNT
- Linq Query with Contains and Nullable Value
- LINQ Query with both CASE statement and SUM function
- Count of distinct with linq to entities and custom IEqualityComparer
- LINQ Query with grouping and ranking
- How to query many-to-many relationship with 'AND' condition using LINQ and Entity Framework
More Query from same tag
- JSON Deserialize Object not working
- c# LINQ returning all joined results
- Enumerable.Cast<T> extension method fails to cast from int to long, why?
- How can I read a CSV from Webserver using c# with LINQ? (ClickOnce deployment)
- C# and Linq to Entities using count in a where lambda statement
- What practices can safeguard against unexpected deferred execution with IEnumerable<T> as argument?
- Linq Aggregate function
- LINQ OrderBy string parameter
- Inspection of Insert Statement When Using LINQ's SubmitChanges
- need to construct a clean Linq query for Graph Data
- Odd Results with LINQ Query in C#
- In linq, how do I take specific parameter out of a list and build new list of different type?
- I want to get most frequent values using LINQ
- Linq to DataTable (GROUP BY) when columns are not known
- Dynamic Where Linq to Entities
- Linq skip if not first page
- Filtering IQueryable sub list
- Non-keyed associations with Entity Framework
- How to flatten a list using linq c#
- c# Dapper - using linq on QueryAsync method
- Grouping persons by age
- Linq data from two table with aggregate functions
- How to check negative value returning from LINQ
- linq summing values by two different ranges
- Does Queryability and Lazy Loading in C# blur the lines of Data Access vs Business Logic?
- C# LINQ query to use previous result if empty
- Linq version of string array any in enum list
- Aging Data Structure in C#
- How to filter entities based on list of items in asp.net core
- Intersection of multiple lists with IEnumerable.Intersect()