I have an array of custom items and then I have an array of objects object[], returned by a function. This object array is indeed of the same Clients type but it is returned as array of object type (I cannot edit this aspect).
I tried with an explicit cast, but I get an exception at runtime saying: cannot convert object[] to clients[].
My goal, once I have both arrays, would be to remove from one list the items that are present in the other list too and make an union, in order to have a unique list.var client = getClients().ToArray(); //Is an array of Clients[]
var normalSearch = getDuplicates().ToArray(); //Is an array of objec开发者_JAVA技巧t[]
//This what I try to achieve,but being object, I cannot invoke "c.ContactId" (Line 4)
var uni = (from c in normalSearch
where !(from d in dupes
select d.ContactId)
.Contains(c.ContactId)
select c).ToArray();
I know that in Linq Union() could exclude automatically duplicate if a primitive type is used, otherwise an extension has to be developed with custom types. But I have not access to the rest of the code, therefore no possibility to change the logic elsewhere.
getDuplicates().Cast<Client>();
var uni = client.Union(normalSearch.Cast<Client>())
.DistinctBy(c => c.ContractId);
The DistinctBy
is in MoreLinq.
If you can't use MoreLinq, you can simply do
var uni = client.Union(normalSearch.Cast<Client>())
.GroupBy(c => c.ContractId)
.Select(g => g.First());
Which is basically their implementation of it.
You can cast the duplicates to clients using linq, and then create a comparer class. I copy and pasted this from the msdn documentation, it may need to be tweaked
var normalSearch = getDuplicates().ToArray().Cast<Clients>();
var client = getClients().ToArray();
var unique = client.Union(normalSearch, new ClientsComparer());
public class ClientsComparer : IEqualityComparer<Clients>
{
public bool Equals(Clients x, Clients y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.ContactId == y.ContactId;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Client client)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Calculate the hash code for the product.
return client.ContactId.GetHashCode();
}
}
精彩评论