In C#, how do I get a distinct value from an IEnumerable using LINQ? - ienumerable

I have an IEnumerable variable that I want to extract a distinct value from. I know all the entries in the rows of the list have the same value, I just need to get that value.
The method returns an IEnumerable.
The row in the IEnumerable is defined as:
QuoteCovId
AdditionalInterestId
AdditionalInterestsAffiliateId
AdditionalInterestsLastName
AdditionalInterestsBusinessAddrLine1
AdditionalInterestsBusinessCity
AdditionalInterestsBusinessState
AdditionalInterestsBusinessZip
Sampel of code:
IadditionalInterestData = AdditionalInterestData.GetAdditionalInterests(MasterPkgID, Requestor);
// Using linq.
var quotes = from ai in IadditionalInterestData
select Distinct(ai.QuoteCovId);
// Iterate thru to get the 1 value.
foreach (int QuoteCovId in quotes)
{
quoteID = QuoteCovId;
}

var quoteId = AdditionalInterestData.GetAdditionalInterests(MasterPkgID, Requestor)
.FirstOrDefault().Select(f => f.QuoteCovId);

But that method:
AdditionalInterestData.GetAdditionalInterests(MasterPkgID, Requestor);
returns me an IEnumerable which I will use further in my application. Which is what I need.
So how will your suggestion still give me that IEnumerable and give me the quote value which happens to be the same in the collection?
var quoteId = AdditionalInterestData.GetAdditionalInterests(MasterPkgID, Requestor).FirstOrDefault().Select(f => f.QuoteCovId);
Also, I just added your line of code as is and I get an error statement.

Related

Entity Framework - Linq to Entities - strange issue with Anonymous function

Following is the code, I am trying:
public List<Movie> GetMovies()
{
Func<Movie, Movie> prepareMovieOutput =
(input) =>
{
input.DisplayHtmlContent = String.Empty;
return input;
};
var moviesOutput = from m in db.Movies.ToList()
select prepareMovieOutput(m);
return moviesOutput.ToList();
}
public List<Movie> SearchMovies(string searchTerm)
{
var moviesOutput = db.Movies.Where(m => m.Name.Contains(searchTerm)).ToList();
return moviesOutput.ToList();
}
The GetMovies function is working properly, as it returns List collection after clearing DisplayHtmlContent field, whereas, SearchMovies function is supposed to return Movie collection with DisplayHtmlContent field, but inspite of that it returns that field empty.
If I set DisplayHtmlContent to some fixed value (like, "ABC"),both GetMovies and SearchMovies return the list with all Movie having DisplayHtmlContent field as "ABC" value. I don't understand why the function defined in one method should affect the other one. and also how to fix this issue?
Ideally, I want GetMovies to hold all Movie with that particular field as empty string, and SearchMovies to hold all Movie with that field containing value.
Any help on this much appreciated.
this was due to the use of repository. I have removed it and it started working fine. with having EF 5, I didn't need to use repository

How do we convert a column from table to an arraylist using ormlite?

I'm trying to convert an entire column values into a arrayList using ormlite on android, is this possible, with direct api?
Using raw results i get close, but not quite:
GenericRawResults<String[]> rawResults =
getHelper().getMyProcessDao().queryRaw(
queryBuild.selectColumns("nid").prepareStatementString());
List<String[]> result = rawResults.getResults();
Hrm. I'm not sure this is what you want. However, one way to accomplish what you ask for specifically is through by using the RawRowMapper which can be passed to ORMLite's DAO method: dao.queryRaw(String, Rowmapper, String...).
Something like the following should work:
RawRowMapper<Integer> mapper = new RawRowMapper<Integer>() {
public Integer mapRow(String[] columnNames, String[] resultColumns) {
// maybe you should verify that there _is_ only 1 column here
// maybe you should handle the possibility of a bad number and throw
return Integer.parseInt(resultColumns[0]);
}
};
GenericRawResults<Integer> rawResults =
getHelper().getMyProcessDao().queryRaw(
queryBuild.selectColumns("nid").prepareStatementString(), mapper);
List<Integer> list = rawResults.getResults();

EF4.1 Code First: Stored Procedure with output parameter

I use Entity Framework 4.1 Code First. I want to call a stored procedure that has an output parameter and retrieve the value of that output parameter in addition to the strongly typed result set. Its a search function with a signature like this
public IEnumerable<MyType> Search(int maxRows, out int totalRows, string searchTerm) { ... }
I found lots of hints to "Function Imports" but that is not compatible with Code First.
I can call stored procedures using Database.SqlQuery(...) but that does not work with output parameters.
Can I solve that problem using EF4.1 Code First at all?
SqlQuery works with output parameters but you must correctly define SQL query and setup SqlParameters. Try something like:
var outParam = new SqlParameter();
outParam.ParameterName = "TotalRows";
outParam.SqlDbType = SqlDbType.Int;
outParam.ParameterDirection = ParameterDirection.Output;
var data = dbContext.Database.SqlQuery<MyType>("sp_search #SearchTerm, #MaxRows, #TotalRows OUT",
new SqlParameter("SearchTerm", searchTerm),
new SqlParameter("MaxRows", maxRows),
outParam);
var result = data.ToList();
totalRows = (int)outParam.Value;

Entity Framework Foreign Key Queries

I have two tables in my entity framework, objects, and parameters which have a foreign key pointing to the object to which they belong. I want to populate a tree with all the attributes of a certain object. So in order to find those I want to do this:
String parentObject = "ParentObjectName";
var getAttributes = (from o in myDB.ATTRIBUTE
where o.PARENT_OBJECT == parentObject
select o);
However when I try to do this I get an error saying it cannot convert from type OBJECT to string, even though in the database this value is stored as a string. I have a workaround where I get an instance of the parentObject, then go through every attribute and check whether it's parent_object == parentObjectInstance, but this is much less efficient than just doing 1 query. Any help would be greatly appreciate, thanks!
Well, PARENT_OBJECT.ToString() can't be called (implicitly or explicitly) in L2E, but if it just returns a property, you can look at that directly:
String parentObject = "ParentObjectName";
var getAttributes = (from o in myDB.ATTRIBUTE
where o.PARENT_OBJECT.NAME == parentObject
select o);
...note the .NAME
Try this:
String parentObject = "ParentObjectName";
var getAttributes = (from o in myDB.ATTRIBUTE
where o.PARENT_OBJECT.ToString() == parentObject
select o);

Problem in LINQ query formation

I have written
List<int> Uids = new List<int>();
Uids = (from returnResultSet in ds.ToList()
from portfolioReturn in returnResultSet.Portfolios
from baseRecord in portfolioReturn.ChildData
select new int
{
id = baseRecord.Id
}).ToList<int>();
Getting error: 'int' does not contain a definition for 'id'
what is the problem that i created?
Thanks
Try this:
List<int> Uids = (from returnResultSet in ds.ToList()
from portfolioReturn in returnResultSet.Portfolios
from baseRecord in portfolioReturn.ChildData
select baseRecord.Id).ToList<int>();
Since you want to get a list of integers you can simply project the Id property from your query and then use the ToList extension method to buffer them into a List<T>. As a side note, are you certain that a List<T> is the right type to use here? You are forgoing the benefit of deferred execution and will not be able to stream these ids if you buffer them into a List<T>.
Your code is trying to instantiate ints, setting an id property that doesn't exist. I think the following is what you need.
Uids = (from returnResultSet in ds.ToList()
from portfolioReturn in returnResultSet.Portfolios
from baseRecord in portfolioReturn.ChildData
select baseRecord.Id).ToList<int>();
The problem is with the: select new int {} part.
Try simply doing:
List<int> Uids = new List<int>();
Uids = (from returnResultSet in ds.ToList()
from portfolioReturn in returnResultSet.Portfolios
from baseRecord in portfolioReturn.ChildData
select baseRecord.Id
)
.ToList<int>();
select new {} syntax is for defining anonymous types (where use is limited to the same function scope).
Andrew.