Can't use == in LINQ Extension Method - linq

I've got the following struct that is the key for my dictionary:
public struct CodeAttribute
{
public int ProcessorId;
public Enums.TransactionType transactionType;
public string ErrorMessage;
}
I've got the following dictionary (one value for now as it's just an example):
var errors = new Dictionary<CodeAttribute, int>
{
{CreateCodeAttributeList(2, Enums.TransactionType.Order, "Invalid ProcessorId sent in the Payment Request"), 100 }
};
And I'm trying to pull out the item in the dictionary that matches on the struct that has a match for both its ProcessorId and TransactionType properties:
private static string GetRelatedMessage(int errorCode, Dictionary<CodeAttribute, int> errorsList)
{
CodeAttribute codeAttribute = errorsList.Where(e => e.Key.ProcessorId == _processorId)
.Where(e => e.Key.transactionType == _transactionType) == errorCode;
return codeAttribute.ErrorMessage;
}
I also want to match on error code as part of the filtering, not just paymentprocessorId and transactionType, just a side note. The item in the dictionary must match all 3 values in order to get the right one in our case.
UPDATE
I tried this as well,and yes I get the error that it can't convert IEnumerable to CodeAtribute
CodeAttribute codeAttributes = errorsList.Where(e => e.Key.ProcessorId == _processorId)
.Where(e => e.Key.transactionType == _transactionType)
.Where(e => e.Value.Equals(errorCode));
UPDATE
with the help of Sam I think this may work
CodeAttribute codeAttribute = errorsList.FirstOrDefault(e => e.Key.ProcessorId ==
_processorId && e.Key.transactionType == _transactionType
&& e.Value == errorCode).Key;

If I understand correctly then you want
var codeAttribute = errorsList.FirstOrDefault(e =>
e.Key.ProcessorId == _processorId
&& e.Key.transactionType == _transactionType
&& e.Value == errorCode);
if(codeAttribute == null)
{
//no item matches in the dictionary.
}
return codeAttribute.Key.ErrorMessage;
Note that codeAttribute will be a KeyValuePair so you will need the codeAttribute.Key.ErrorMessage as your return value.
You don't need to use Where as that will return an IEnumerable so this won't work if you want a single item.

You probably need to go with something like this:
CodeAttribute codeAttribute = errorsList.FirstOrDefault(e => e.Key.ProcessorId == _processorId && e.Key.transactionType ==_transactionType)

While the other answers are correct, I would probably write it like this:
var errorMessage = errorsList
.Where(e => e.Key.ProcessorId == _processorId
&& e.Key.transactionType == _transactionType
&& e.Value == errorCode)
.Select(e => e.Key.ErrorMessage)
.FirstOrDefault();
That is, push the condition to filter earlier on, select the data I want from that result-set, and then take the first result (should one exist) of the transformed data.
Since the IEnumerable queries are lazy then this will still stop on the first sucessfully filtered object.
Since the source is a Dictionary, it may be also prudent to set up a relevant Equals/GetHashCode and structure the code such that it will be used.

Related

automatically expand the result of an odata function

I defined an odata function to mimic $search which is not supported yet in the recent core release. I want to return the core entity plus an expanded entity which would translate into a js object on each Person in the returned json values array.
I tried odata/People/MyNS.Find(text='john', orderby='CreatedOn')?$expand=CurrentWork where CurrentWork is on People, but that did not work.
Thoughts on how to do this?
// my controller code for the function
[HttpGet]
public ActionResult<ICollection<People>> Find([FromODataUri] string text,
[FromODataUri] string orderBy)
{
if (text == null || text.Length == 0)
return Get().ToList();
if (orderBy == null || orderBy.Length == 0)
orderBy = "CreatedOn";
return _db.People
.Where(p => p.FirstName.Contains(text)
|| p.LastName.Contains(text)
|| p.Nickname.Contains(text))
.OrderBy(orderBy)
.Take(5000)
.ToList();
}
Regular expansion of CurrentWork in a non-function works fine e.g. odata/People?$expand=CurrentWork.
By looking at the Linq query, it's fetching only People data and not any of it's child collections. You should use Include to fetch data for child collections along with parent entity like below. Read more on loading related entities here.
// my controller code for the function
[HttpGet]
public ActionResult<ICollection<People>> Find([FromODataUri] string text,
[FromODataUri] string orderBy)
{
if (text == null || text.Length == 0)
return Get().ToList();
if (orderBy == null || orderBy.Length == 0)
orderBy = "CreatedOn";
return _db.People
.Where(p => p.FirstName.Contains(text)
|| p.LastName.Contains(text)
|| p.Nickname.Contains(text))
.Include(p => p.CurrentWork) // I have added this line
.OrderBy(orderBy)
.Take(5000)
.ToList();
}
Note: You still need to use $expand=CurrentWork as query string. Without this query string, server will remove child collections before sending response to client.
Here's what I came up with in the end. I noticed that the included entities were pulling in alot of data from the database so I reduced down the pull quite a bit by being specific. Include just pulled everything and I could not reduce the Include down directly so I had to use a Select.
[HttpGet]
public IOrderedQueryable Find2([FromODataUri] string text,
[FromODataUri] string orderBy)
{
if (orderBy == null || orderBy.Length == 0)
orderBy = "CreatedOn DESC";
if (text == null || text.Length == 0)
return Get().OrderBy(orderBy);
var r = LikeToRegular(text);
return _db.People
.AsNoTracking() // can't use if using lazy loading
.Select(p => new
{
p.FirstName,
p.LastName,
p.Nickname,
p.CreatedOn,
p.CurrentWork.Title,
p.CurrentWork.Company.CompanyName
})
// Forces local computation, so pulls entire people dataset :-(
.Where(x => Regex.IsMatch(x.LastName ?? "", r)
|| Regex.IsMatch(x.FirstName ?? "", r, RegexOptions.IgnoreCase)
|| Regex.IsMatch(x.Nickname ?? "", r, RegexOptions.IgnoreCase)
|| Regex.IsMatch($"{x.FirstName} {x.LastName}", r,
RegexOptions.IgnoreCase))
.OrderBy(orderBy);
}
// Allow some wildcards in the search...
public static String LikeToRegular(String value)
{
return "^" + Regex.Escape(value)
.Replace("_", ".")
.Replace("%", ".*") + "$";
}

Escape null values LINQ

I have an issue with this linq expression:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => sitecoreContext.GetItem<Inv>(new ID(x).Guid))
.ToList();
How can I check for null into the .Select? SitecoreContext.GetItem(new ID(x).Guid)) to crash (because items being unpublished, or created but not published) so I need a way to verify first if the item exist, and only then to make the select.
Thank you.
When you call SitecoreContext.GetItem<T>, in the background SitecoreContext gets the item from the database and then it casts it to the T type. And from what I can see, it can throw an exception if there is no item with the specified ID.
What you can do to avoid this exception is split what SitecoreContext does and execute it on your own with a null check in between:
Execute GetItem first
Do the null check
Cast the item to your type:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => sitecoreContext.Database.GetItem(new ID(x)))
.Where(x => x != null)
.Select(x => sitecoreContext.Cast<Inv>(x))
.ToList();
You can filter all non-null items using a where statement.
var nonNull = list.Where(element => element != null);
I usually use an extension method for this:
public static class EnumerableExtensions
{
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> enumerable)
where T: class
{
return enumerable.Where(element => element != null);
}
}
Given your example, you could use the statement like this:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.WhereNotNull()
.Select(x => sitecoreContext.GetItem<Inv>(new ID(x).Guid))
.ToList();
You Can Check Null Using null coalescing operator or ternary Operator in Linq Example is Given Below
`var productTypes = from ProductDto e in Product
select new
{
Id = e.Product != null ? e.Product.ID : 0,
Name = "xyz"
};`

How to get all items with the same value in list of lists c# LINQ?

I have a to add a specific requirement in a piece of code already implemented.
The data structure is something of this sort:
public class Module
{
public string Type;
public string ID;
public List<Point> Points = new List<Point>();
}
public class Point
{
public string Type;
public string Location;
public string Connection;
}
Originally LINQ was used to return all modules which certain characteristics
List<Module> miList = Modules.Where(m => m.Type != null
&& m.ID == "A"
&& m.Points.Where(t => t.Connection == ""
&& SimilarPoint(t.Type, x).ToList())
.Count() > 0)
.ToList();
with x an input to the function. The new requirement dictates that the modules returned shall all have points with Connection equal to "" and the same value in the Location field.
It seemed to me that the SelectMany could be used to this end, but I am not getting what I expected.
How should the function above be modified?
Thanks in advance
Not exactly sure what the SimilarPoint(t.Type, x) does here.
May be you should try something like this and find out if it works for you -
var resultSet = Modules.Where(m => !string.IsNullOrEmpty(m.Type) && m.ID.Equals("A"))
.Select(n =>
new Module {
Type=n.Type,
ID=n.ID,
Points= n.Points.Where(p => String.IsNullOrEmpty(p.Connection) && String.IsNullOrEmpty(p.Location)).ToList()
})
.ToList();
You said all the returned modules have the same Location, but that doesn't explain how you select which Location so I arbitrarily picked the first matching module's location:
var miQuery1 = Modules.Where(m => m.Type != null
&& m.ID == "A"
&& m.Points.Where(t => t.Connection == ""
&& SimilarPoint(t.Type, x).ToList()).Count() > 0)
.Where(m => m.Points.All(p => p.Connection == ""));
var miQuery2 = miQuery1.Where(m => m.Location == miQuery1.First().Location);
List<Module> miList = miQuery2.ToList();

Cannot convert from IEnumerable<List> to List

I am working on these lists to get an item that matches the selected item from the combobox.
private void InitializaMessageElement()
{
if (_selectedTransactionWsName != null)
{
get a transaction webservice name matching the selected item from the drop down here the output=TestWS which is correct
var getTranTypeWsName = TransactionTypeVModel
.GetAllTransactionTypes()
.FirstOrDefault(transTypes =>
transTypes.WsMethodName == _selectedTransactionWsName);
Loop the list of wsnames from the treenode list. Here it gives me all the node I have which is correct.
var wsNameList = MessageElementVModel
.GetAllTreeNodes().Select(ame =>
ame.Children).ToList();//. == getTranTypeWsName.WsMethodName);
find the getTranTypeWsName.WsMethodName in the wsNameList. Here is where I have the problem:
var msgElementList = MessageElementVModel.GetAllTreeNodes()
.Select(ame => ame.Children).Where(c =>
{
c.Where(d => getTranTypeWsName != null && d.Name == getTranTypeWsName.WsMethodName);
return false;
});
my MsgElement list:
var _msgElementList = new ObservableCollection<MessageElementViewModel>(msgElementList);
this.messageElements = _msgElementList;
NotifyPropertyChanged("MessageElements");
}
Here it is returning wrong data. It returns all the list I have a non filtered one.
Why is my out put inconsistent? I am new to LINQ.
This part of your code seems problematic:
var msgElementList = wsNameList.SingleOrDefault(x =>
{
x.Where(ame => ame.Name == getTranTypeWsName.WsMethodName);
return true;
});
You were expecting a list but you used the SingleOrDefault(), which is meant to be used in retrieving a single record.
Try this, which will retrieve msgElementList. No need to get all tree nodes first and store it in wsNameList:
// Assumed that Name is a property of Children
var msgElementList = MessageElementVModel.GetAllTreeNodes()
.Select(ame => ame.Children).Where(c => c.Name == getTranTypeWsName.WsMethodName).ToList();
Here is a solution:
var msgElementList = wsNameList.SelectMany(x => x.Where(ame => getTranTypeWsName != null && ame.Name == getTranTypeWsName.WsMethodName)).ToList();

Set the list value using linq

Hi I want to set the value in the list of objects that matches the given condition in the where clause.Is it possible?
Other work around is to get the list of objects using where clause and then iterate using for Or foreach loop and update the value.
listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest);
I have list listOfRequestAssigned of objects and want to update some propery of the objects that match my search criteria.
class Request
{
bool _requestCompleted;
int _requestedNumber;
public int RequestedNumber
{
get { return _requestedNumber; }
set { _requestedNumber = value; }
}
public bool RequestCompleted
{
get { return _requestCompleted; }
set { _requestCompleted = value; }
}
}
I want to update RequestCompleted property of all objects that match criteria using Linq
You can use ForEach in Linq
listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest).ToList().ForEach(x => x.RequestCompleted = true);
if you have more than one update to do,
listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest).ToList().ForEach(x => { x.RequestCompleted = true; x.OtherProperty = value; } );
Where(...) give you a query, not a Request or a List<Request>. Use FirstOrDefault() if you want to have one (or 0) result, or ToList() if you want to have a list of results on wich you can use ForEach().
In general Linq is a query- not an update tool, but you can use a foreach:
var currentRequests = listOfRequestAssigned
.Where(x => x.RequestedNumber == CurrentRequest);
foreach(var req in currentRequests)
{
req.RequestCompleted = true;
}
Since you have specific collection of type List, you can just use ForEach and a conditional set:
listOfRequestAssigned.Foreach(x => { if (x.RequestedNumber == CurrentRequest) x.RequestCompleted = true;}});
If you had a more generic collection IEnumerable, you can use Select in Linq to build a projection where property will be set as desired (original collection will be left untouched!):
listOfRequestAssigned
.Where(x => x.RequestedNumber == CurrentRequest)
.Select(x => { x.RequestCompleted = true; return x; })
You can use to assign boolean value by following on comparing time. This is the very simplest and smart way for bool property.
listOfRequestAssigned.ForEach(x => x.RequestCompleted = x.RequestedNumber
== CurrentRequest);

Resources