How to select the first three elements of a IEnumerable object? - c#

That's it. The question is in the title
I was looking for a cleaner way than the using for...break;
thanks

This should do it!
var items = new List<int>(){ 1, 2, 3, 4, 5 };
var results = items.Take(3);

Related

How to assert all items in a collection to be different using fluent-assertions?

I want to make sure that all items in a collection to be different. How to do that?
Let's say:
IEnumerable collection = new[] { 1, 2, 5, 8 };
collection.Should().BeAllDifferent(); // NOTE: BeAllDifferent doesn't exist

Grouping including non grouped field using Linq/Lambda

I have a list which has data
list1 [{actId: 1, dt:'10/5/2015', hr:3}, {actId: 1, dt:'10/5/2015', hr:5},
{actId: 3, dt:'10/4/2015', hr:3}, {actId: 4, dt:'10/6/2015', hr:1},
{actId: 4, dt:'10/6/2015', hr:8}, {actId: 1, dt:'10/2/2015', hr:3}]
I am using a Linq query to group the data
var dat= list1.AsEnumerable().GroupBy(t=> new{t.actId, t.dt})
.Select(x=> new
{
tId=x.Key.techId,
dat=x.Key.dt,
thrs=x.Sum(y=>y.hr)
});
This works and gives me result but gives me the results grouping both "actId" and "dt" while I want to just group them by "actId". If I change the query to
var dat= list1.AsEnumerable().GroupBy(t=> new{t.actId})
.Select(x=> new
{
tId=x.Key.techId,
dat=x.dt,
thrs=x.Sum(y=>y.hr)
});
I get intellisense error for x.dt saying "Cant Resolve Symbol "dt"
Please let me know how to change the query so I can include x.dt in it without grouping by it.
So output should look like
[ {actId:1, [{dt: 10/5/2015, hr:8}, {dt: 10/2/2015, hr:38}]},
{actId: 3, [{dt: 10/4/2015, hr:3}]},
{actId: 4 [{dt: 10/6/2015 hr: 9}]}]
Thanks
It's because there isn't a single 'dt', there is a group of them, this will return them all as a group for you:
var dat=list1.AsEnumerable()
.GroupBy(t=> t.actId)
.Select(x=> new
{
actId=x.Key,
dat=x.Select(x=>new { x.dt,x.hr}).ToList()
});
This is as close as I can get to your output. It'll look like:
[ {actId:1, dat:[{dt: 10/5/2015, hr:8}, {dt: 10/2/2015, hr:38}]},
{actId: 3, dat:[{dt: 10/4/2015, hr:3}]},
{actId: 4, dat:[{dt: 10/6/2015 hr: 9}]}]

IEnumerable - exclude using an array

Does anyone know if it's possible to create a new IEnumerable by using an array parameter to exclude values.
For instance, below is an example of how I imagine it would look.
class Item
{
public int id { get; set; }
public string name { get; set; }
}
IEnumerable looks like this:
item1 {id = 1}
item2 {id = 2}
item3 {id = 3}
I want to create a new IEnumerable but exclude the id numbers in the array.
Made up code to suggest idea:
Int32[] arrayList = {1,2};
var newIEnumerable = _exisitingIEnumerable.Where(o => (o.id NOT IN arrayList));
Looking at your question again, when the element type of _exisitingIEnumerable is not the same as that of arrayList, you will need to use Where to filter out the elements of arrayList
_exisitingIEnumerable.Where(o => !arrayList.Contains(o.Id))
Original answer:
_exisitingIEnumerable.Except(arrayList)
will return the distinct elements from _exisitingIEnumerable that are not in arrayList
If you need duplicates, you can use
_exisitingIEnumerable.Where(o => !arrayList.Contains(o))
What's wrong with the approach you suggested in the question? You can use Where and check if the array contains the value. Below the example using List as a target collection:
var myList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
int[] myArray = { 1, 2, 3 };
var result = new List<int>(myList.Where(n => !myArray.Contains(n)));

How do I update/add items in/to an IObservable<int> dynamically?

I have an observable collection to which I want to keep feeding objects and they should reach observers even after someone has subscribed to it (which ofcourse is the main aim of an observable). How do I do it?
In the following program, after the subscription has happened I want to feed in 3 more numbers which should reach observers. How do I do this?
I don't want to go via the route where I implement my own Observable class by implementing IObservable<int> and use Publish method? Is there any other way to achieve this?
public class Program
{
static void Main(string[] args)
{
var collection = new List<double> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var observableCollection = collection.ToObservable();
observableCollection.Subscribe(OnNext);
//now I want to add 100, 101, 102 which should reach my observers
//I know this wont' work
collection.Add(100);
collection.Add(101);
collection.Add(102);
Console.ReadLine();
}
private static void OnNext(double i)
{
Console.WriteLine("OnNext - {0}", i);
}
}
This is what I'd do:
var subject = new Subject<double>();
var collection = new List<double> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var observableCollection = collection
.ToObservable()
.Concat(subject); //at the end of the original collection, add the subject
observableCollection.Subscribe(OnNext);
//now I want to add 100, 101, 102 which should reach my observers
subject.OnNext(100);
subject.OnNext(101);
subject.OnNext(102);
Generally, if you can observe whatever is producing the additional input, you'd want to concat that observable, rather than imperatively pushing these values into a subject, but sometimes that's not practical.

Is there a C# equivalent to C++'s std::set_difference?

If so, what is it?
EDIT: In response to comment below:
var tabulatedOutputErrors = from error in outputErrors
group error by error into errorGroup
select new { error = errorGroup.Key, number = errorGroup.Count() };
var tabulatedInputErrors = from error in inputErrors
group error by error into errorGroup
select new { error = errorGroup.Key, number = errorGroup.Count() };
var problems = tabulatedOutputErrors.Except(tabulatedInputErrors);
You can expand out the counts if you need to.
LINQ has the Enumerable.Except extension method, which seems to be what you're looking for.
Example:
var list1 = new int[] {1, 3, 5, 7, 9};
var list2 = new int[] {1, 1, 5, 5, 5, 9};
var result = list1.Except(list2); // result = {3, 7}
Alternative:
From .NET 3.5 onwards there also exists the HashSet<T> class (and also the similar SortedSet<T> class in .NET 4.0. This class (or rather the ISet<T> interface in .NET 4.0) has an ExceptWith method which could also do the job.
Example:
var set1 = new HashSet<int>() {1, 3, 5, 7, 9};
var set2 = new HashSet<int>() {1, 1, 5, 5, 5, 9};
set1.ExceptWith(set2); // set1 = {3, 7}
Of course, it depends on the context/usage whether this approach is more desirable. The efficiency benefit (doing the difference operation in-place and using hash codes) in most cases is probably negligible. Either way, take your pick. :)

Categories