public static List<Reservations> getReservations(int reservationId)
{
return hoteldb.hotel_reservations.Where(x => x.reservation_id == reservationId).ToList();
}
I converted the values, I made sure that everything is good but to no avail.
It's not really working even the code below:
public List<Reservations> getReservations(int reservationId)
{
return hoteldb.hotel_reservations.Where(x => x.reservation_room_desc == "sdfsfs").ToList();
}
Maybe getReservations() should use the type : List<hotel_reservations> ?
public List<hotel_reservations> getReservations(int reservationId)
{
var y = hoteldb.hotel_reservations
.Where(x => x.reservation_room_desc == "sdfsfs")
.ToList();
return y;
}
Related
How to convert this sample foreach into lambda expression?
foreach (ADOMD.Member iMember in pMemberCollection)
{
decimal lDimensionValue = 0;
if (Decimal.TryParse(iMember.Name, out lDimensionValue))
lDimensionValues.Add(lDimensionValue);
}
lDimensionValues.Sort();
ADOMD.Member is a interface looks like
[TypeLibType(xxx)]
[Guid("xxxxx")]
public interface Member
{
[DispId(0)]
string Caption { get; }
[DispId(1610743817)]
int ChildCount { get; }
string Name { get; }
[DispId(1610743812)]
Member Parent { get; }
[DispId(1610743819)]
bool ParentSameAsPrev { get; }
[DispId(1610743815)]
}
lDimensionValues =
pMemberCollection
.Cast<ADOMD.Member>()
.Select(iMember => {
decimal lDimensionValue = 0;
if (Decimal.TryParse(iMember.Name, out lDimensionValue))
return (decimal?)lDimensionValue;
else return null;
})
.Where(x => x != null)
.Select(x => x.Value)
.OrderBy(x => x)
.ToList();
Very ugly and verbose. If we had a TryParseDecimal method it would be cleaner.
This is not a perfect case for LINQ. Among other reasons due to the legacy collection that requires a Cast apparently.
Had to try to do this in as few lines as possible, interesting problem, i would not convert your method to LINQ though, if it already works (what works works)
lDimensionValues = pMemberCollection.Where(a => {
decimal lDimensionValued;
return decimal.TryParse(a.Name, out lDimensionValued);
}).Select(a=> decimal.Parse(a.Name)).Sort();
I have a list of lists which looks like the following
public class FilteredVM
{
public int ID { get; set; }
public string Name { get; set; }
public string Number { get; set; }
}
List<List<FilteredVM>> groupedExpressionResults = new List<List<FilteredVM>>();
I would like to Intersect the lists within this list based upon the ID's, whats the best way to tackle this?
Here's an optimized extension method:
public static HashSet<T> IntersectAll<T>(this IEnumerable<IEnumerable<T>> series, IEqualityComparer<T> equalityComparer = null)
{
if (series == null)
throw new ArgumentNullException("series");
HashSet<T> set = null;
foreach (var values in series)
{
if (set == null)
set = new HashSet<T>(values, equalityComparer ?? EqualityComparer<T>.Default);
else
set.IntersectWith(values);
}
return set ?? new HashSet<T>();
}
Use this with the following comparer:
public class FilteredVMComparer : IEqualityComparer<FilteredVM>
{
public static readonly FilteredVMComparer Instance = new FilteredVMComparer();
private FilteredVMComparer()
{
}
public bool Equals(FilteredVM x, FilteredVM y)
{
return x.ID == y.ID;
}
public int GetHashCode(FilteredVM obj)
{
return obj.ID;
}
}
Like that:
series.IntersectAll(FilteredVMComparer.Instance)
You could just write
series.Aggregate((a, b) => a.Intersect(b, FilteredVMComparer.Instance))
but it 'd be wasteful because it'd have to construct multiple sets.
Intersect will work when the type are dead equals, which in your case won't apply because you haven't implemented the GetHashCode and Equals methods, which is the best and complete way.
Thus, If you only intended to take elements that contains in both lists, than the following solution will suit you right.
Assuming list1 and list2 are type List<FilteredVM> than, The most simple way, will be doing this:
var intersectByIDs = list1.Where(elem => list2.Any(elem2 => elem2.ID == elem.ID));
If you are a fan of one-liner solutions you can use this:
List<FilteredVM> result = groupedExpressionResults.Aggregate((x, y) => x.Where(xi => y.Select(yi => yi.ID).Contains(xi.ID)).ToList());
And if you just want the IDs you can just add .Select(x => x.ID), like this:
var ids = groupedExpressionResults.Aggregate((x, y) => x.Where(xi => y.Select(yi => yi.ID).Contains(xi.ID)).ToList()).Select(x => x.ID);
Working Demo
I am using this function to get a list of groups
public static IEnumerable<QuizGroups> GetGroups(string sectorId)
{
var Quizes = _QuizDataSource.AllQuizGroups.Where(x => x.Subtitle == sectorId);
return Quizes;
}
But this returns all, I want to return the first group in the list.
How do i change the statement to get the first group?
You can use First or FirstOfDefault and return enumerable with single element:
public static IEnumerable<QuizGroups> GetGroups(string sectorId)
{
return new[]
{
_QuizDataSource.AllQuizGroups.FirstOrDefault(x => x.Subtitle == sectorId)
};
}
Also note:
If you plan to always return one element only, consider refactoring GetGroups method to return QuizGroups only.
AllQuizGroups property may be null. Add null-check for that property.
You should consider using C# Naming Conventions.
Local variable names should be Camel Cased; so it should be: var quizes.
Property _QuizDataSource should be renamed to QuizDataSource if it is public or _quizDataSource or quizDataSource if it is private.¹
¹ — It's a heat debate whether to use _ or not for private fields, read more at: https://stackoverflow.com/questions/1630844/c-sharp-member-variables-fields-naming-convention
Try First or FirstOrDefault.
public static IEnumerable<QuizGroups> GetGroups(string sectorId)
{
var Quizes = _QuizDataSource.AllQuizGroups.FirstOrDefault(x => x.Subtitle == sectorId);
return Quizes;
}
public static QuizGroups GetGroups(string sectorId)
{
return QuizDataSource.AllQuizGroups.FirstOrDefault(
x => x.Subtitle == sectorId);
}
or add an indexer to the collection class (assuming MyQuizGroupsCollection is the type of _QuizDataSource
public class MyQuizGroupsCollection: IEnumerable<QuizGroups>
{
// other stuff
public QuizGroups this[string sectorId]
{ get { return FirstOrDefault(x => x.Subtitle == sectorId); } }
}
... then you could simply write
var Quizes = _QuizDataSource[sectorId];
I'm not really sure, why grouping by IEnumerable<string> does not work. I provide custom IEqualityComparer, of course.
public class StringCollectionEqualityComparer : EqualityComparer<IEnumerable<string>>
{
public override bool Equals(IEnumerable<string> x, IEnumerable<string> y)
{
if (Object.Equals(x, y) == true)
return true;
if (x == null) return y == null;
if (y == null) return x == null;
return x.SequenceEqual(y, StringComparer.OrdinalIgnoreCase);
}
public override int GetHashCode(IEnumerable<string> obj)
{
return obj.OrderBy(value => value, StringComparer.OrdinalIgnoreCase).Aggregate(0, (hashCode, value) => value == null ? hashCode : hashCode ^ value.GetHashCode() + 33);
}
}
class A
{
public IEnumerable<string> StringCollection { get; set; }
}
IEnumerable<A> collection = // collection of A
var grouping = collection.GroupBy(obj => a.StringCollection, StringCollectionEqualityComparer.Default).ToList();
(ToList() is to force evaluation, I have breakpoints in StringCollectionEqualityComparer, but unfortunately, they're not invoked, as expected)
When I group collection in this dumb way, it actually works.
var grouping = collection.GroupBy(obj => String.Join("|", obj.StringCollection));
Unfortunately, obviously it is not something I want to use.
By not working, I mean the results are not the ones I expect (using dumb way, the results are correct).
StringCollectionEqualityComparer.Default is a valid alternative way to access EqualityComparer<IEnumerable<string>>.Default, since the latter is a base class of the former. You need to create an instance of StringCollectionEqualityComparer, simply using new StringCollectionEqualityComparer(), instead.
I have a list of objects, GroupStudentStatus, that I need to make distinct.
I wrote the class below to do this.
The 2 attributes that are relevant are GroupStudentStatus.IsLastActionRemoved (DateTime) and GroupStudentStatus.Student.Guid.
protected List<GroupStudentStatus> RemovedStudents
{
get
{
return AllStudents.Where(s => s.IsLastActionRemoved).Distinct().OrderByDescending(d => d.LastActionDate).ToList();
}
}
public class GroupStudentStatusComparer : IEqualityComparer<GroupStudentStatus>
{
public GroupStudentStatus Compare(GroupStudentStatus x, GroupStudentStatus y)
{
//get the student that was last removed
if (!Equals(x, y))
{
return x.LastActionDate > y.LastActionDate ? x : y;
}
return x;
}
public bool Equals(GroupStudentStatus x, GroupStudentStatus y)
{
return x.Student.Guid.Equals(y.Student.Guid);
}
public int GetHashCode(GroupStudentStatus obj)
{
return obj.Student.Guid.GetHashCode();
}
}
I think this is right, except I can't figure out how to test it.
I was trying to do this:
return AllStudents.Where(s => s.IsLastActionRemoved)
.Distinct(new GroupStudentStatusComparer((x, y) => x.Compare(x,y)))
.OrderByDescending(d => d.LastActionDate).ToList();
return AllStudents.Where(s => s.IsLastActionRemoved)
.Distinct(new GroupStudentStatusComparer())
.OrderByDescending(d => d.LastActionDate)
.ToList();
return AllStudents.Where(s => s.IsLastActionRemoved).GroupBy(gss => gss.Student).Select(g => new GroupStudentStatus(g.Key, g.Select(gss2 => gss2.LastActionDate).Max(), true)).OrderByDescending(d => d.LastActionDate).ToList();
Ended up using groupBy.