lest say I have two lists
List1:
"Tom",
"Frank",
"Lacey"
List2:
"Frank",
"Tom"
what would be the query needed to show that Tom and Fran are being repeated?
The lists that I am trying to compare are very big and if I do something like:
var q = from a in List1
from b in List2
where a.Name == b.Name
select a;
this takes a long time.
To see what values are duplicated across lists, you can use
var results = list1.Intersect(list2);
If you were otherwise interested in matching the items and doing something with each, you could use Join
var results = from item1 in list1
join item2 in list2
on item1 equals item2
select new
{
// include what you want here
};
In your case, since you are dealing with a list of strings, Intersect seems like the appropriate course of action. If you were dealing with matching lists of objects on a common key, you might opt to join the lists and project the results.
You should use Intersect:
var items = List1.Intersect(List2); // Tom, Frank
You can use intersect:
List<string> list3 = list1.Intersect(list2).ToList();
Related
list1 contains userid and username
list2 contains userids
Need to display the list1 where its userid is included in list2.
string userids = "user1,user2,user3";
var list2 = userids.Split(',').Select(userid => userid.Trim()).ToList();
list1 = list1.Any(x => x.UserID)... //Got stuck here
Better use HashSet<T> for search:
string userids = "user1,user2,user3";
var userIdSet = new HashSet<string>(userids.Split(',').Select(userid => userid.Trim()));
list1 = list1.Where(x => userIdSet.Contains(x.UserID)).ToList();
Another way is Enumerable.Join which is more efficient if the lists are pretty large:
var containedUsers = from x1 in list1
join x2 in list2 on x1.UserId equals x2
select x1;
list1 = containedUsers.ToList();
I assume that the UserID's in list2 are unique(otherwise use Distinct). If not, joining them might cause duplcicate items in list1.
Its easy to get stuck on So you need to check list2 contains the item you picked.
found = list1.Where( x => list2.contains(x.UserID));
Method Any returns bool, it
Determines whether any element of a sequence satisfies a condition
Return Value
Type: System.Boolean
true if any elements in the source sequence pass the test in the specified predicate; otherwise, false.
Method Where
Filters a sequence of values based on a predicate.
So you can use Any inside Where to filter only results that contains inside list2.
list1 = list1.Where(l1 => list2.Any(l2 => l2 == l1.UserID)).ToList();
References: Enumerable.Any(Of TSource) Method, Enumerable.Where(Of TSource) Method
I have data from two data structures that I would like to join with respect to date. Each data structure contains 88 values and every date in one structure has a corresponding date in the other structure. However, when I try to join them, the list with the joined result contains 90 values. In other words the result contains two extra values. When I inspect the values in the joined list it seems that it contains two extra values at the start of the list that are identical to the first "expected" joined value.
Any ideas what might be wrong?
Here is the join expression that I am using:
//Joins vib and RPM with respect to date
var joinedVibRPM = serie.Value.Values.Join(
RPMSeriesOne.Values,
_vib => _vib.DateTime,
_rpm => _rpm.DateTime,
(_vib, _rpm) => new { vib = _vib.Value, rpm = _rpm.Value }).ToList();
You can explain the result when your input sets have duplicate entries. Consider for example this join of two list with four items each (using strings, not DateTime for better readability):
var items1 = new { "A", "B", "C", "C" };
var items2 = new { "A", "B", "B", "C" };
If you perform this join:
var joinedItems =
from item1 in items1
join item2 in items2 on item1 equals item2
select item1 + item2;
Your result will be:
{ "AA", "BB", "BB", "CC", "CC" }
You will find "BB" twice because it is repeated in the secod list and "CC" twice because it is repeated in the first list. In total you will get 5 items.
If you have any duplicate dates in either structure then one element in one structure will match 2 (or more) elements in the other structure. This will give you more than 88 results.
Check your structures for distinct values:
serie.Value.Values.Distinct().Count();
and
RPMSeriesOne.Values.Distinct().Count();
One of these results will likely be less than 88 indicating the presence of duplicates.
I have two separate IEnumerable lists having dynamic values:
First list is IEnumerable<string> SubHeadId having data like
[0]->1
[1]->4
Second list is IEnumerable<string> SubHeadId having data like
[0]->100
[1]->233
I want to join these two lists into single list having data like
[0]->1,100
[1]->4,233
How can I join lists. Please Guide.
Thanks
The proper way to achieve this is using the Zip() extension method:
var firstList = new List<string>() { "1", "4" };
var secondList = new List<string>() { "100", "233" };
var combined = firstList.Zip(secondList, (f, s) => f + ", " + s ).ToList();
It's important to notice here that:
If you happen to have two collections with an unequal number of elements, the Zip method will only continue to the shortest index where both elements exist. No errors will occur if the two collections are uneven.
My code
query1 = select value1, value2 from dbo.animal where animalname="tiger";
query2 = select value1, value2 from dbo.animal where animalname="lion";
List<Animal> list1 = db.ExecuteStoreQuery<Animal>(query1).ToList();
List<Animal> list2 = db.ExecuteStoreQuery<Animal>(query2).ToList();
// list1.Count = 1 list1[0].value1 = "a" list1[0].value2 = "b"
// list2.Count = 1 list2[0].value1 = "a" list2[0].value2 = "b"
// Now I would like to compare list1 and list2 to see if they are equal
var list3 = list1.Except(list2);
//At this point list3 is containing both list1 and list2 and using var made it
//GenericList not the same type of list as List1 and List2
I tried List list3 = list1.Except(list2) but I get compile error.
So the question is how do I find out if list1 is equal to list2?
I was hoping list3 would be the differences between list1 and list2 and therefore if the lists are equal list3.count() should be 0.
The nice thing about my data is I believe data in from query1 and query should be both in order and result in only 1 record each.
First of all, checking if the results of Except are empty cannot answer the "are these two lists equal?" question. It answers the "does list2 contain all the elements of list1?", which is not the same, because list2 may contain additional elements.
The nice thing about my data is I believe data in from query1 and query should be both in order and result in only 1 record each.
You can compare two identically ordered lists for equality using SequenceEqual, like this:
bool areIdentical = list1.SequenceEqual(list2);
If the ordering is different, you can also force it to be the same with OrderBy:
bool areIdentical = list1
.OrderBy(animal=>animal.Id)
.SequenceEqual(list2.OrderBy(animal=>animal.Id));
I've got 2 generic lists that do not contain the all fields of the same type
IList<Category> and List<CategoriesRow>Categories
categoryList = IList<Category>
but both have common fields Name and ID.
I want to compare list Categories with categoryList and find those from categoryList where categoryList[index].ID does not exist in the list of all Categories of ID. For all those that do not exist in Categories, I will have to remove them from CatgoryList.
I had a previous post in which I was given examples of LINQ, but the problem is I have to use Dynamic, implying that I am passing categoryList and Categories as Dynamic.
Can anyone give me an example how to go about the above as I have no idea how to do it.
Use the .Except LINQ operator.
Like this:
var uniqueList = list1.Except(list2);
Not sure what you mean by "I have to use Dynamic".
This is a standard LINQ operation available to all types that implement IEnumerable.
Here's a good article on doing it.
let say you have a list1 and list2 like this:
IList<Category> list1 = new List<Category>();
IList<CategoryRow> list2 = new List<CategoryRow>();
//populate lists here....
Now to select from list1 only those items that have a matching Id in list2, you could do
list1 = list1.Where(c => list2.Exists(cr => cr.Id == c.Id)).ToList();
Hope that answers your question